-1

I have an algorithm that is calculating:

result = int(14949283383840498/5262*27115)

The correct result should be 77033412951888085, but Python3.8 gives me 77033412951888080

I also have tried the following:

>>> result = 77033412951888085
>>> print(result)
77033412951888085
>>> print(int(result))
77033412951888085
>>> print(float(result))
7.703341295188808e+16
>>> print(int(float(result)))
77033412951888080

It seems the problem occours when I cast the float to int. What am I missing?

PS: I have found that using result = 14949283383840498//5262*27115 I get the right answer!

2 Answers2

0

Casting is not the issue. Floating-point arithmetic has limitations with respect to precision. See https://docs.python.org/3/tutorial/floatingpoint.html

Need to either use integer division or use the decimal module which defaults to using 28 places in precision.

Using integer division

result = 14949283383840498 // 5262 * 27115
print(result)

Output:

77033412951888085

Using decimal module

from decimal import Decimal
result = Decimal(14949283383840498) / 5262 * 27115
print(result)

Output:

77033412951888085
CodeMonkey
  • 22,825
  • 4
  • 35
  • 75
0

It is an precision limitation :

result = 14949283383840498/5262*27115
result
7.703341295188808e+16

In this case, result is a float. You can see that the precision is of 15 digits. Convert that to int, you see that the last non zero digit is 8, it is correct to what result: float show when printed.

Try the following:

print(sys.float_info.dig)
15

dig is the maximum number of decimal digits that can be faithfully represented in a float.

A very good explanation regarding this issue is available here.

But there are ways to do better with Python, see from the Python's doc:

For use cases which require exact decimal representation, try using the decimal module which implements decimal arithmetic suitable for accounting applications and high-precision applications.

Another form of exact arithmetic is supported by the fractions module which implements arithmetic based on rational numbers (so the numbers like 1/3 can be represented exactly).

If you are a heavy user of floating point operations you should take a look at the NumPy package and many other packages for mathematical and statistical operations supplied by the SciPy project

Gannon
  • 68
  • 6