如何防止numpy中十进制数字的自动移位

how to prevent automatic shift in decimal numbers in numpy

这是我的代码:

y = np.array([-3.44 , 1.16 , -0.81])
y = np.exp(y)
print(y)

对于这个块,我得到了以下结果

[0.03206469 3.18993328 0.44485807]

但是,当我将3.91添加到列表中时,结果发生了变化

x = np.array([-3.44 , 1.16 , -0.81 , 3.91])
x = np.exp(x)
print(x)

结果:

[3.20646853e-02 3.18993328e+00 4.44858066e-01 4.98989520e+01]

我怎样才能阻止这种变化?

您可以使用 np.set_printoptions:

>>> x = np.array([-3.44 , 1.16 , -0.81 , 3.91])
>>> x = np.exp(x)
>>> print(x)
[3.20646853e-02 3.18993328e+00 4.44858066e-01 4.98989520e+01]

>>> np.set_printoptions(suppress=True, precision=8)

>>> print(x)
[ 0.03206469  3.18993328  0.44485807 49.89895197]

解释:

十进制舍入不能总是用二进制精确表示,因此您会看到一些浮点数不一致。例如:

>>> 0.1 + 0.2
0.30000000000000004

鉴于这些不一致,numpy 默认表示科学记数法中的浮点数。我在上面展示的方式只是将打印选项设置为您想要的方式,但数组中的实际表示不会改变。

np.set_printoptions(suppress=True) 抑制科学记数法,默认情况下将浮点数抑制到 8 小数位,因此从技术上讲,在这种情况下不需要 precision 参数:

>>> np.set_printoptions(suppress=True)
>>> x
[ 0.03206469  3.18993328  0.44485807 49.89895197]

我添加了 precision 以防万一您在打印时需要所需的精度。

>>> np.set_printoptions(suppress=True, precision=2)
>>> x
array([ 0.03,  3.19,  0.44, 49.9 ])

在此处了解有关浮点运算的更多信息:

  1. Is floating point math broken?

  2. https://0.30000000000000004.com/