Generating Random number

Hi

Presumably using grand() is recommended. The default is mt = Mersenne-Twister. To seed the generator, I see that:S = grand(“getsd”); returns a vector of length 625.

Classically one seeds the generator with the current time-date, as in
n=getdate(“s”)
grand(“setsd”,n)
… as it is described in the help, but n is just a number, and ‘mt’ will not accept this and returns: grand: Wrong value for the last 1 input argument(s).

Am I supposed to put the getdate into the first element, or am I supposed to generate an array of 625 time-date numbers to properly seed this generator?

With kind regards,
Claus

Hi Claus,

You have to give an integer, and getdate("s") is not (in general):

--> n=getdate('s')

 n = 

   1.717D+09

--> n-floor(n)

 ans = 

   0.4710000

So, just take the integer part before feeding grand:

grand("setsd",floor(n))

S.

This works, at least now there is no error message anymore. I think the official documentation could be updated:

With kind regards,
Claus

Yes we will fix this in the doc (see Fix failing example using setsd key (!948) · Merge requests · scilab / scilab · GitLab)

S.

Hi Stéphane
I see how simply floor(n) was added.

Dear Scilabers, here’s a fun script for generating a number of tickets and selecting some winners (a raffle). I am randomizing both the list of tickets as well as the selection of winners. Is this a good or bad idea?

// raffle.sce

r = grand(“getgen”); // default mt = Mersenne-Twister, period about 2^19937
S = grand(“getsd”); // seed, returns vector, length 625
n=getdate(“s”); // seed based on date and time (increase randomness)
grand(“setsd”,floor(n));// set the seed in the random number generator
nt = 102; // number of tickets
tickets = grand(1, “prm”, 1:nt); // shuffle order of tickets

w = 4; // number of winners
Low = 1; // lower bound value (ticket number 1)
High = nt; // upper bound value, max < 2,147,483,561
Y = grand(w, 1, “uin”, Low, High); // uniform distribution [m,n]

disp(‘Winning tickets:’)
for i = 1:w do
disp(tickets(Y(i)));
end

With kind regards,
Claus

Hi

I found one problem with above code, that the same ticket can be chosen twice:

Y = grand(w, 1, “uin”, Low, High); // uniform distribution [m,n]

Is there a way to prevent this?

With kind regards,
Claus

Hi

Sorry, I found that once the tickets are shuffled, they are sufficiently randomized, I can just print the first four tickets as winners:

disp(‘Winning tickets:’)
for i = 1:w do
disp(tickets(i));
end

With kind regards,
Claus

To avoid to resample more than once the same element, try samwr
x = Low:High;
Y = samwr(w, 1, x);

I’ve seen that samwr uses the seed set by grand(“setsd”,floor(n)).

1 Like