20.3.2 Generating uniformly distributed random numbers
The rand or
random or
hasard command produces random
numbers, chooses random elements from a list, or creates functions
that produce random numbers.
To produce random real numbers:
-
rand takes two optional arguments.
-
Optionally, a and b, two real numbers. By default,
a=0 and b=1.
- rand([a,b]) returns a number in [a,b) randomly and
with equal probability.
To produce random integers:
-
rand takes
n, an integer.
- rand(n) returns a random integer in [0,n) (or (n,0] if
n is negative).
Examples
(to produce a random number in [0,1)).
(to produce a random number in [1,1.5)).
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, enter:
Another way to get a random integer in a specified interval is with
the randint command.
-
randint takes two arguments:
n1 and n2, two integers.
- randint(n1,n2) returns a random
integer between n1 and n2, inclusive.
Example
-
To make a function which produces random numbers, rand takes
a..b, a range with real numbers a and b.
- rand(a..b) returns a function
which will generate a random number in the interval from a to b.
Example
-
To choose elements without replacement,
rand takes two or three arguments:
-
p, a positive integer.
- Either: n1 and n2, two integers.
- or: L, a list.
- rand(p,n1,n2) returns a list of p distinct
random integers from n1 to n2.
- rand(L) returns p elements without replacement from the list L.
Examples
rand(3,["a","b","c","d","e","f","g","h"]) |
The list can have repeated elements.
rand(4,["r","r","r","r","v","v","v"]) |
The sample
command will also randomly select items from a list without replacement.
-
sample takes two arguments:
-
L, a list.
- p, an integer.
- sample(L,p) returns a list of p items chosen
randomly from L, without replacement.
Note that with the sample command, the list
comes first and then the integer.
Example
sample(["r","r","r","r","v","v","v"],4) |