Can I specify a numpy dtype when generating random values?

lmjohns3 picture lmjohns3 · Apr 29, 2014 · Viewed 22.8k times · Source

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.)

Answer

emeth picture emeth · Apr 29, 2014

Q: is it possible to specify a dtype for random numbers when I create them.

A: No it isn't. randn accepts the shape only as randn(d0, d1, ..., dn)

Simply try this:

x = np.random.randn(10, 10).astype('f')

Or define a new function like

np.random.randn2 = lambda *args, dtype=np.float64: np.random.randn(*args).astype(dtype)
x = np.random.randn2(10, 10, dtype='f')

If you have to use your code on the post, try this code instead

x = np.zeros((10, 10), dtype='f')
x[:] = np.random.randn(*x.shape)

This assigns the results of randn to the memory allocated by np.zeros