如何在Python中使用精确的浮点运算?

2024-10-01 17:33:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python中遇到了浮点运算的问题。 我要解的方程如下:

-a *((x-m)*110.0*(1-m))**b +a*((x-m)*110.0*(1-m))**c
a is a really large positive number (in the hundred thousands)
b is 1.0000002
c is 0.9999998

当我在excel中这样做的时候,我得到了准确的结果,但是当我在python中这样做的时候,我得到了完全不准确的结果。

在我乘以-a和a之前,每个单独部分的结果都是完全相同的。 所以((x-m)110.0(1-m))**b和((x-m)110.0(1-m))**c与它们的excel计算值完全相同,但当它们乘以大数时,它们完全改变。

我该怎么做?我必须用另一种语言吗?这个问题是只在python中存在还是在所有语言中都存在?

编辑:excel中的公式与python中的完全相同。完全一样。这些数字也是一样的,直到我乘以a和-a,然后它们都是5点左右的。在excel中,x=0.5和m=0.265的答案约为0.47,而python的答案约为-0.67


Tags: the答案in语言编辑numberisexcel
3条回答

根据定义,浮点运算并非完全100%精确,因为值用分数表示。看看关于Python float limitations的文章,以及另一篇more general article

很难理解你在寻找什么样的精度,但我想你也可以看看decimal module.-

It offers several advantages over the float datatype:

Decimal “is based on a floating-point model which was designed with people in mind, and necessarily has a paramount guiding principle – computers must provide an arithmetic that works in the same way as the arithmetic that people learn at school.” – excerpt from the decimal arithmetic specification.

Decimal numbers can be represented exactly. In contrast, numbers like 1.1 and 2.2 do not have an exact representations in binary floating point. End users typically would not expect 1.1 + 2.2 to display as 3.3000000000000003 as it does with binary floating point.

The exactness carries over into arithmetic. In decimal floating point, 0.1 + 0.1 + 0.1 - 0.3 is exactly equal to zero. In binary floating point, the result is 5.5511151231257827e-017. While near to zero, the differences prevent reliable equality testing and differences can accumulate. For this reason, decimal is preferred in accounting applications which have strict equality invariants.

The decimal module incorporates a notion of significant places so that 1.30 + 1.20 is 2.50. The trailing zero is kept to indicate significance. This is the customary presentation for monetary applications. For multiplication, the “schoolbook” approach uses all the figures in the multiplicands. For instance, 1.3 * 1.2 gives 1.56 while 1.30 * 1.20 gives 1.5600.

mpmath可以是答案

Mpmath is a pure-Python library for multiprecision floating-point arithmetic. It provides an extensive set of transcendental functions, unlimited exponent sizes, complex numbers, interval arithmetic, numerical integration and differentiation, root-finding, linear algebra, and much more.

http://code.google.com/p/mpmath/

相关问题 更多 >

    热门问题