# Producing uniformly distributed random numbers: rand random alea hasard sample

### 8.3.1 Producing uniformly distributed random numbers: rand random alea hasard sample

The rand command produces random numbers, chooses random elements from a list, or creates functions that produce random numbers.
random and hasard are synonyms for rand.

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.

#### Examples.

- Input:
  rand()
  (to produce a random number in [0,1)). Output (for example):

  0.528489416465

- Input:
  rand(1,1.5)
  (to produce a random number in [1,1.5)). Output (for example):

  1.0012010464

To produce random integers:

- rand takes one argument:
  n, an integer.
- rand(n) returns a random integer in [0,n) (or (n,0] if n is negative).

#### Example.

Input:

rand(5)

Output (for example):

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, you can enter:
Input:

6 + rand(11-6)

Output (for example):

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.

Input:

randint(6,10)

Output (for example):

8

To make a function which produces random numbers:

- rand takes one argument:
  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.

Input:

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

Output (for example):

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.

- Input:
  rand(2,1,10)
  Output (for example):

  ⎡ ⎣ | 2,9 | ⎤ ⎦

- Input:
  rand(3,["a","b","c","d","e","f","g","h"])
  Output (for example):

  ⎡ ⎣ | "e","g","a" | ⎤ ⎦

- The list can have repeated elements.
  Input:
  rand(4,["r","r","r","r","v","v","v"])
  Output (for example):

  ⎡ ⎣ | "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.

Input:

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

Output (for example):

⎡ ⎣ | "v","v","v","r" | ⎤ ⎦