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

rand()

you might get, for example,

0.93233498279

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

rand(1,1.5)

for example, you might get

1.27419309644

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

r:=rand(1.0..2.5)

you will get

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

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

r()

might return

1.76314622024

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

rand(5)

for example, you might get

2

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

7

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

randint(6,10)

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

rand(2,1,10)

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

[2,9]

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

rand(3,["a","b","c","d","e","f","g","h"])

you might get

["c","b","e"]

The list can have repeated elements; if you enter

rand(4,["r","r","r","r","v","v","v"])

you might get

["v","v","r","v"]

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

sample(["r","r","r","r","v","v","v"],4)

you might get

["v","r","r","r"]

Previous Up Next