Over the past years the random number generation in NumPy has gotten an overhaul. The modern way of setting up reproducible random numbers is now something like this:
# Set up random number generator
import numpy as np
stream = np.random.PCG64DXSM
seed = 42
rng = np.random.Generator(stream(seed))
# Draw random numbers from various distributions
a = rng.uniform (0, 1, size=10) # uniform distribution
b = rng.normal (0, 1, size=10) # normal distribution
c = rng.rayleigh(1, size=10) # Rayleigh distribution
...
This work great. The three arrays a
, b
and c
all contain double-precision floats, i.e. their dtype
is np.float64
. How would I go about changing this to e.g. np.float32
?
I can of course just convert the results to 32-bit, but that's not optimal (and this doesn't work at all if we extend the question to 128-bit). Getting 32-bit results are supported in the docs, but I can't find out how to do it using the above system of first defining an rng using np.random.Generator(stream(seed))
. Another doc entry states that
Optional dtype argument that accepts np.float32 or np.float64 ...
but again I cannot seem to find where in the above such an argument may be placed.
A similar question has been asked before, but all results pertain to older NumPy interfaces than the modern one showcased above.
To be concrete, let's focus on the newest version of NumPy (1.22), which do come with some changes to the random number generation, though I think only bug fixes.