将np.random.normal()添加到每个元素时,为什么会在数组中得到整数?

当我运行此代码时

import numpy as np

y = np.arange(1,11)
for i in range(len(y)):
    y[i] = y[i] + np.random.normal()

print(y)

我得到输出

[ 2  1  2  3  2  6  6  7 10 10]

为什么所有的数字都y被转换成整数?np.random.normal()显然做返回浮动。

回答

这是因为y您的示例中的数组隐式设置为dtype=int. 因此,在做 时y[i] = y[i] + np.random.normal(),它等价于int = int + float; 即 a在存储之前float必须被类型转换为 an int

您可以通过手动指定dtypewhile 创建numpy阵列来规避此问题。

import numpy as np

y = np.arange(1, 11, dtype=float)
for i in range(len(y)):
    y[i] = y[i] + np.random.normal()

print(y)
# Sample output: [ 2.16400377  1.5604771   2.69698066  4.17251939  4.13071869  5.99501597  7.06189783  7.69103035 10.51589948 10.31083259]


以上是将np.random.normal()添加到每个元素时,为什么会在数组中得到整数?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>