【问题标题】:how to prevent automatic shift in decimal numbers in numpy如何防止numpy中十进制数的自动移位
【发布时间】:2023-11-16 18:13:01
【问题描述】:

这是我的代码:

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]

如何防止这种变化?

【问题讨论】:

  • 这是显示格式的变化,而不是值的变化。

标签: python numpy scientific-notation


【解决方案1】:

你可以使用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/

【讨论】:

  • 谢谢,您介意解释一下这个问题的概念吗?
  • @alifallahi 添加了。
最近更新 更多