Generating uniformly distributed random numbers

### 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

rand()

(to produce a random number in [0,1)).

0.528489416465 |  |  |  |  |  |  |  |  |  |

rand(1,1.5)

(to produce a random number in [1,1.5)).

1.0012010464 |  |  |  |  |  |  |  |  |  |

rand(5)

3 |  |  |  |  |  |  |  |  |  |

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:

6+rand(11-6)

7 |  |  |  |  |  |  |  |  |  |

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

randint(6,10)

8 |  |  |  |  |  |  |  |  |  |

- 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

r:=rand(1.0..2.5):; r()

1.68151313369 |  |  |  |  |  |  |  |  |  |

- 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(2,1,10)

| ⎡ ⎣ | 2,9 | ⎤ ⎦

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

| ⎡ ⎣ | “e”,“g”,“a” | ⎤ ⎦

The list can have repeated elements.

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

| ⎡ ⎣ | “r”,“v”,“v”,“r” | ⎤ ⎦

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)

| ⎡ ⎣ | “v”,“v”,“v”,“r” | ⎤ ⎦