Previous Up Next

7.3.1  Producing uniformly distributed random numbers: rand random alea hasard

The rand (or random) command will produce a number in [0,1) randomly and with equal probability. If you enter


you might get, for example,


If you want a random number in a different interval, you can give rand two real arguments; rand(a,b) will return a random number from the interval [a,b). If you enter


for example, you might get


If you give rand an interval, then you will get function which will generate a random number in the interval. If you enter


you will get

// Success (NULL)->rand(1.0,2.5)

and you can get a random number in the interval by calling the function;


might return


If you want to generate a random integer, then rand(n) (for integer n) will return a random integer in [0,n) (or (n,0] if n is negative). If you enter


for example, you might get


You can then use rand to find a random integer in a specified interval; if you want an random integer between 6 and 10, inclusive, for example, you can enter

6 + rand(11-6)

You might get


Alternatively, the randint will give you a random integer in a given interval; randint(n1,n2) will return a random integer between n1 and n2, inclusive; to get a random integer from 6 to 10, you could enter


The rand command can also choose elements without replacement. If you give rand three integer arguments, rand(p,n1,n2) then it will return p distinct random integers from n1 to n2. If you enter


for example, you will get 2 distinct random numbers from 1 to 10; perhaps


You can also choose (without replacement) random elements of a given list. For this, you give rand, a postive integer n and a list L; rand(n,L) will then return n random elements from the list. If you enter


you might get


The list can have repeated elements; if you enter


you might get


The sample command will also randomly select items from a list without replacement. With the sample command, the list comes first and then the integer. If you enter


you might get


Previous Up Next