Previous Up Next

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:

To produce random integers:

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.

Example

randint(6,10)
     
8           

Example

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

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.

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”
          

Previous Up Next