Yakitori
Yakitori

Reputation: 127

Big number division leads to unexact result

I am test a solidity program, which deals with very large numbers (1e17).

The formula I'm testing is the following : int(1e17*(100-3)/(100-1))

WolframAlpha and the Solidity language tell me that it's equivalent to 97979797979797979.

The test fails however because Python returns 97979797979797984.

How can I get the right value with Python ?

Upvotes: 0

Views: 133

Answers (1)

Peter O.
Peter O.

Reputation: 32878

In this case, the fractions module works well here, since its division between two numbers is exact, in that it preserves the precision of the result.

>>> from fractions import Fraction
>>> int(Fraction(10)**17*(100-3)/(100-1))
97979797979797979
>>> 

(Here we avoid notation like 1e17 because it may resolve to an inexact float value.)

Upvotes: 3

Related Questions