生成随机值时可以指定numpy dtype吗? [英] Can I specify a numpy dtype when generating random values?

查看:126
本文介绍了生成随机值时可以指定numpy dtype吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个随机值的numpy数组,并将它们添加到包含32位浮点数的现有数组中.我想使用与目标数组相同的dtype生成随机值,这样就不必手动转换dtype.目前,我正在这样做:

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)

但是randn(实际上没有任何numpy.random方法)不接受dtype自变量.

but randn (and actually none of the numpy.random methods) does not accept a dtype argument.

我的具体问题是,创建随机数时是否可以为随机数指定dtype,而不必调用astype? (我的猜测是随机数生成器的长度为64位,因此这样做实际上没有任何意义,但我想我会问是否可能.)

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

推荐答案

问:创建随机数时是否可以为随机数指定dtype.

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

A:不,不是. randn仅接受形状为randn(d0,d1,...,dn)

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

只需尝试一下:

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)

这会将randn的结果分配给np.zeros

这篇关于生成随机值时可以指定numpy dtype吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆