Learning Scientific Programming with Python (2nd edition)
E6.18: Random sampling of evenly-spaced real numbers
NumPy's random integer methods can be used for sampling from a set of evenly-spaced real numbers, though it requires a bit of extra work: to pick a number from n
evenly-spaced real numbers between a
and b
(inclusive), use:
In [x]: a + (b - a) * (np.random.random_integers(n) - 1) / (n - 1)
For example to sample from $[\frac{1}{2}, \frac{3}{2}, \frac{5}{2}, \frac{7}{2}]$,
In [x]: a, b, n = 0.5, 3.5, 4
In [x]: a + (b - a) * (np.random.random_integers(n, size=10) - 1) / (n - 1)
array([ 1.5, 0.5, 1.5, 1.5, 3.5, 2.5, 3.5, 3.5, 3.5, 3.5])
Note: the numpy.random.random_integers()
function is now deprecated and may be removed in future versions of Python. The current recommended call is to np.random.randint(1, n+1)
instead:
In [x]: a + (b - a) * (np.random.randint(1, n+1) - 1) / (n - 1)