Can I specify a numpy dtype when generating random values?

£可爱£侵袭症+ 提交于 2019-12-09 00:30:40

问题


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


回答1:


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, **kwarg: np.random.randn(*args).astype(kwarg.get('dtype', np.float64))
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




回答2:


Let me begin by saying that numpy now supports dtypes for random integers. This enhancement can be tracked through Issue #6790 on numpy's github. But as of today, this facility is not available for the gaussian RNG. I needed this same facility so I wrote this patch for numpy, https://gist.github.com/se4u/e44f631b249e0be03c21c6c898059176

The patch only adds support for generating float values and it does not handle other data types, but it might still be helpful to someone.




回答3:


np.random.randn function randomly initializes the array object of a given shape to a "np.float64" You can find this out yourself by doing as follows:

a = np.random.rand(2,3)
b = a[1,2]
print (type(b))
print (type(a))

output as follows:

<class 'numpy.float64'>
<class 'numpy.ndarray'>


来源:https://stackoverflow.com/questions/23355433/can-i-specify-a-numpy-dtype-when-generating-random-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!