With numpy, how can I generate an array of random floats within a range?
Say I'd like to generate floats within 8 to 10. The seed is set
eg = np.random.default_rng(567)
how can I generate floats with eg?
CodePudding user response:
You can do it by setting a seed to an existing random number generator by calling np.random.seed(567)
each time you want to restart the sequence.
If you'd like to create a new Generator, you can do it as in your question:
rng = np.random.default_rng(seed=567)
Then, you can sample random numbers just by calling uniform
method which takes min
, max
and size
parameters. In your case:
size = (3, 4)
rng.uniform(8, 10, size)
will return an array with 3 row and 4 columns that consists of floats between 8 and 10. Apart from uniform distribution there are many more predefined ones that are accessible the same way as uniform
(https://numpy.org/doc/stable/reference/random/generator.html#distributions).
You can also do it with random
that also can take an argument of size
. In your case:
rng.random(size) * 2 8
will do the same.
CodePudding user response:
np.random.random()
generates floats between 0 and 1. So, multiply by 2 and add 8.
def make_8_10():
return np.random.random() * 2 8