我正在创建一个随机值的 numpy
数组,并将它们添加到包含 32 位 float 的现有数组中。我想使用与目标数组相同的 dtype 生成随机值,这样我就不必手动转换 dtypes。目前我这样做:
import numpy as np
x = np.zeros((10, 10), dtype='f')
x += np.random.randn(*x.shape).astype('f')
我想做而不是最后一行是这样的:
x += np.random.randn(*x.shape, dtype=x.dtype)
但是 randn
(实际上没有一个 numpy.random
方法)不接受 dtype
参数。
我的具体问题是,是否可以在创建随机数时为随机数指定 dtype,而无需调用 astype
? (我的猜测是随机数生成器是 64 位长,所以这样做并没有什么意义,但我想我会问是否可能。)
最佳答案
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)
试试这个:
x = np.random.randn(10, 10).astype('f')
或者定义一个新的函数,比如
np.random.randn2 = lambda *args, dtype=np.float64: np.random.randn(*args).astype(dtype)
x = np.random.randn2(10, 10, dtype='f')
如果您必须在帖子中使用您的代码,请尝试使用此代码
x = np.zeros((10, 10), dtype='f')
x[:] = np.random.randn(*x.shape)
这会将 randn
的结果分配给 np.zeros
关于python - 我可以在生成随机值时指定一个 numpy dtype 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23355433/