如何设置numpy浮点精度?

use*_*298 14 floating-point numpy

我只是用两种方式计算了相同的数字,但是在numpy中,它会出错

[[ 0.910221324013388510820732335560023784637451171875]]
[[-0.9102213240133882887761274105287156999111175537109375]]
Run Code Online (Sandbox Code Playgroud)

这个数字与e ^( - 15)相同,但之后有所不同.我该如何处理这个错误?

有没有办法限制浮点精度?

由于我使用这些数字计算指数,即使很小的差异也会导致令人沮丧的错误......

ali*_*i_m 15

您是否关心结果的实际精度,或者从两次计算中得到完全相同的数字?

如果您只想要相同的数字,您可以使用np.around()将结果四舍五入到一些适当的小数位数.但是,通过这样做,您只会降低结果的精度.

如果您确实想要更精确地计算结果,可以尝试使用np.longdouble输入数组的类型,这取决于您的体系结构和编译器,可能会为您提供80位或128位浮点表示,而不是标准64 -bit np.double*.

您可以使用以下方法比较精确的小数位数np.finfo:

print np.finfo(np.double).precision
# 15

print np.finfo(np.longdouble).precision
# 18
Run Code Online (Sandbox Code Playgroud)

请注意,并非所有numpy函数都支持long double - 有些将向下转换为double.


*但是,一些编译器(如Microsoft Visual C++)将始终long double视为同义词double,在这种情况下,np.longdouble和之间的精度不会有差异np.double.

  • 如果"`numpy.longdouble`引用你的C编译器调用`long double`"的任何类型,如你的链接中所述,那么不幸的是,对于一些C编译器,它不会比`double`(例如Visual Studio)更精确.仍然,+1回答问题. (2认同)

Tah*_*aha 5

在正常的numpy使用中,数字是两倍。这意味着精度将小于16位数字。这是一个包含相同问题的已解决主题...

如果您需要提高精度,可以使用符号计算...。图书馆mpmath ...是一个安静的好地方。优点是您可以使用无限精度。但是,计算速度比numpy的速度慢。

这是一个例子:

# The library mpmath is a good solution
>>> import sympy as smp
>>> import mpmath as mp

>>> mp.mp.dps = 50  # Computation precision is 50 digits
# Notice that the difference between x and y is in the digit before last (47th)
>>> x = smp.mpmath.mpf("0.910221324013388510820732335560023784637451171875")
>>> y = smp.mpmath.mpf("0.910221324013388510820732335560023784637451171865")
>>> x - y  # Must be equal to 1e-47 as the difference is on the 47th digit
mpf('1.000014916280995001003481719184726944958705912691304e-47')
Run Code Online (Sandbox Code Playgroud)

你不能用numpy做得更好。您可以更精确地计算指数。

smp.exp(x).evalf(20) = 2.4848724344693696167
Run Code Online (Sandbox Code Playgroud)