如何设置numpy浮点精度? [英] how set numpy floating point accuracy?

查看:2139
本文介绍了如何设置numpy浮点精度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只用两种方式计算了相同的数字,但在numpy中,它会产生一个错误

  [[0.910221324013388510820732335560023784637451171875]] 
[[-0.9102213240133882887761274105287156999111175537109375]]

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



有什么办法可以限制浮点数的准确性吗?

指数使用这些数字,即使是很小的差异导致令人沮丧的错误...

解决方案

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



如果您只需要相同的数字,您可以使用 np.around() to round结果到一些适当的小数位数。但是,这样做只会降低结果的精度。



如果您真的想更精确地计算结果,可以尝试使用 np.longdouble 键入您的输入数组,其中,取决于您的体系结构和编译器,可能会给你一个80位或128位的浮点表示,而不是标准的64位 np.double *。



您可以使用 np.finfo

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

print np.finfo(np.longdouble).precision
#18

请注意,并不是所有的numpy函数都会支持long double,有些会减少double。






*然而, ome编译器(例如Microsoft Visual C ++)将始终将 long double 视为 double 的同义词,在这种情况下,在 np.longdouble np.double 之间的精确度没有差别。


I just calculated the same number in two ways, but in numpy, it makes an error

[[ 0.910221324013388510820732335560023784637451171875]]
[[-0.9102213240133882887761274105287156999111175537109375]]

this number is the same up to e^(-15), but differs afterwards. How do I treat this error?

Is there any way to limit floating point accuracy?

Since I calculate exponential using these numbers, even little differences result in frustrating errors...

解决方案

Do you care about the actual precision of the result, or about getting the exact same digits back from your two calculations?

If you just want the same digits, you could use np.around() to round the results to some appropriate number of decimal places. However, by doing this you'll only reduce the precision of the result.

If you actually want to compute the result more precisely, you could try using the np.longdouble type for your input array, which, depending on your architecture and compiler, might give you an 80- or 128-bit floating point representation, rather than the standard 64-bit np.double*.

You can compare the approximate number of decimal places of precision using np.finfo:

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

print np.finfo(np.longdouble).precision
# 18

Note that not all numpy functions will support long double - some will down-cast it to double.


*However, some compilers (such as Microsoft Visual C++) will always treat long double as synonymous with double, in which case there would be no difference in precision between np.longdouble and np.double.

这篇关于如何设置numpy浮点精度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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