I'm creating a numpy
array of random values and adding them to an existing array containing 32-bit floats. I'd like to generate the random values using the same dtype as the target array, so that I don't have to convert the dtypes manually. Currently I do this:
import numpy as np
x = np.zeros((10, 10), dtype='f')
x += np.random.randn(*x.shape).astype('f')
What I'd like to do instead of the last line is something like:
x += np.random.randn(*x.shape, dtype=x.dtype)
but randn
(and actually none of the numpy.random
methods) does not accept a dtype
argument.
My specific question is, is it possible to specify a dtype for random numbers when I create them, without having to call astype
? (My guess is that the random number generator is 64 bits long, so it doesn't really make sense to do this, but I thought I'd ask if it's possible.)
x
when you do the operation in-place, there's absolutely no need forastype
, simply dox += np.random.randn(*x.shape)
, and see for yourself thatx.dtype
doesn't change. – Platelayer