Can I specify a numpy dtype when generating random values?

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)