I'm having this issue in python with float arithmetic.
The equation I'm solving goes as follows:
-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
When I do this in excel I get accurate results but when I do it in python I get completely inaccurate results.
The results are exactly the same for each separate part until I multiply by -a and a.
So ((x-m)110.0(1-m))**b and ((x-m)110.0(1-m))**c are exactly the same as their excel calculated values but when they're multiplied by the large number they completely change.
How do I do this? do I have to use a different language? Is this problem only in python or is it in all languages?
Edit: It is the exact same equation in excel as in python. Exactly the same. The numbers are also the same until I multiply by a and -a. then they are both off by 5 point something. The answer in excel is around 0.47 for x=0.5 and m = 0.265 while the answer for python is around -0.67
解决方案
It is quite hard to understand what precision you are looking for but i think that you can also take a look at the 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.