Random Numbers with Python API

– Carl Witty (2008-03): new file

This module has the same functions as the Python standard module module{random}, but uses the current sage random number state from module{sage.misc.randstate} (so that it can be controlled by the same global random number seeds).

The functions here are less efficient than the functions in module{random}, because they look up the current random number state on each call.

If you are going to be creating many random numbers in a row, it is better to use the functions in module{sage.misc.randstate} directly.

Here is an example:

(The imports on the next two lines are not necessary, since function{randrange} and function{current_randstate} are both available by default at the code{sage:} prompt; but you would need them to run these examples inside a module.)

sage: from sage.misc.prandom import randrange
sage: from sage.misc.randstate import current_randstate
sage: def test1():
....:    return sum([randrange(100) for i in range(100)])
sage: def test2():
....:    randrange = current_randstate().python_random().randrange
....:    return sum([randrange(100) for i in range(100)])

Test2 will be slightly faster than test1, but they give the same answer:

sage: with seed(0): test1()
sage: with seed(0): test2()
sage: with seed(1): test1()
sage: with seed(1): test2()
sage: timeit('test1()') # random
625 loops, best of 3: 590 us per loop
sage: timeit('test2()') # random
625 loops, best of 3: 460 us per loop

The docstrings for the functions in this file are mostly copied from Python’s file{random.py}, so those docstrings are “Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007 Python Software Foundation; All Rights Reserved” and are available under the terms of the Python Software Foundation License Version 2.

sage.misc.prandom.betavariate(alpha, beta)

Beta distribution.

Conditions on the parameters are alpha > 0 and beta > 0. Returned values range between 0 and 1.


sage: betavariate(0.1, 0.9)
sage: betavariate(0.9, 0.1)

Choose a random element from a non-empty sequence.


sage: [choice(list(primes(10, 100))) for i in range(5)]
[17, 47, 11, 31, 47]

Exponential distribution.

lambd is 1.0 divided by the desired mean. (The parameter would be called “lambda”, but that is a reserved word in Python.) Returned values range from 0 to positive infinity.


sage: [expovariate(0.001) for i in range(3)]
[118.152309288166, 722.261959038118, 45.7190543690470]
sage: [expovariate(1.0) for i in range(3)]
[0.404201816061304, 0.735220464997051, 0.201765578600627]
sage: [expovariate(1000) for i in range(3)]
[0.0012068700332283973, 8.340929747302108e-05, 0.00219877067980605]
sage.misc.prandom.gammavariate(alpha, beta)

Gamma distribution. Not the gamma function!

Conditions on the parameters are alpha > 0 and beta > 0.


sage: gammavariate(1.0, 3.0)
sage: gammavariate(3.0, 1.0)
sage.misc.prandom.gauss(mu, sigma)

Gaussian distribution.

mu is the mean, and sigma is the standard deviation. This is slightly faster than the normalvariate() function, but is not thread-safe.


sage: [gauss(0, 1) for i in range(3)]
[0.9191011757657915, 0.7744526756246484, 0.8638996866800877]
sage: [gauss(0, 100) for i in range(3)]
[24.916051749154448, -62.99272061579273, -8.1993122536718...]
sage: [gauss(1000, 10) for i in range(3)]
[998.7590700045661, 996.1087338511692, 1010.1256817458031]

getrandbits(k) -> x. Generates a long int with k random bits.


sage: getrandbits(10)
sage: getrandbits(200)
sage: getrandbits(10)
sage.misc.prandom.lognormvariate(mu, sigma)

Log normal distribution.

If you take the natural logarithm of this distribution, you’ll get a normal distribution with mean mu and standard deviation sigma. mu can have any value, and sigma must be greater than zero.


sage: [lognormvariate(100, 10) for i in range(3)]
[2.9410355688290246e+37, 2.2257548162070125e+38, 4.142299451717446e+43]
sage.misc.prandom.normalvariate(mu, sigma)

Normal distribution.

mu is the mean, and sigma is the standard deviation.


sage: [normalvariate(0, 1) for i in range(3)]
[-1.372558980559407, -1.1701670364898928, 0.04324100555110143]
sage: [normalvariate(0, 100) for i in range(3)]
[37.45695875041769, 159.6347743233298, 124.1029321124009]
sage: [normalvariate(1000, 10) for i in range(3)]
[1008.5303090383741, 989.8624892644895, 985.7728921150242]

Pareto distribution. alpha is the shape parameter.


sage: [paretovariate(3) for i in range(1, 5)]
[1.0401699394233033, 1.2722080162636495, 1.0153564009379579, 1.1442323078983077]
sage.misc.prandom.randint(a, b)

Return random integer in range [a, b], including both end points.


sage: [randint(0, 2) for i in range(15)]
[0, 1, 0, 0, 1, 0, 2, 0, 2, 1, 2, 2, 0, 2, 2]
sage: randint(-100, 10)

Get the next random number in the range [0.0, 1.0).


sage: [random() for i in [1 .. 4]]
[0.111439293741037, 0.5143475134191677, 0.04468968524815642, 0.332490606442413]
sage.misc.prandom.randrange(start, stop=None, step=1)

Choose a random item from range(start, stop[, step]).

This fixes the problem with randint() which includes the endpoint; in Python this is usually not what you want.


sage: randrange(0, 100, 11)
sage: randrange(5000, 5100)
sage: [randrange(0, 2) for i in range(15)]
[0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1]
sage: randrange(0, 1000000, 1000)
sage: randrange(-100, 10)
sage.misc.prandom.sample(population, k)

Choose k unique random elements from a population sequence.

Return a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices).

Members of the population need not be hashable or unique. If the population contains repeats, then each occurrence is a possible selection in the sample.

To choose a sample in a range of integers, use xrange as an argument (in Python 2) or range (in Python 3). This is especially fast and space efficient for sampling from a large population: sample(range(10000000), 60)


sage: sample(["Here", "I", "come", "to", "save", "the", "day"], 3)
['Here', 'to', 'day']
sage: from six.moves import range
sage: sample(range(2^30), 7)
[357009070, 558990255, 196187132, 752551188, 85926697, 954621491, 624802848]
sage.misc.prandom.shuffle(x, random=None)

x, random=random.random -> shuffle list x in place; return None.

Optional arg random is a 0-argument function returning a random float in [0.0, 1.0); by default, the sage.misc.random.random.


sage: shuffle([1 .. 10])
sage.misc.prandom.uniform(a, b)

Get a random number in the range [a, b).

Equivalent to code{a + (b-a) * random()}.


sage: uniform(0, 1)
sage: uniform(e, pi)
0.5143475134191677*pi + 0.48565248658083227*e
sage: RR(_)
sage.misc.prandom.vonmisesvariate(mu, kappa)

Circular data distribution.

mu is the mean angle, expressed in radians between 0 and 2*pi, and kappa is the concentration parameter, which must be greater than or equal to zero. If kappa is equal to zero, this distribution reduces to a uniform random angle over the range 0 to 2*pi.


sage: [vonmisesvariate(1.0r, 3.0r) for i in range(1, 5)]  # abs tol 1e-12
[0.898328639355427, 0.6718030007041281, 2.0308777524813393, 1.714325253725145]
sage.misc.prandom.weibullvariate(alpha, beta)

Weibull distribution.

alpha is the scale parameter and beta is the shape parameter.


sage: [weibullvariate(1, 3) for i in range(1, 5)]
[0.49069775546342537, 0.8972185564611213, 0.357573846531942, 0.739377255516847]