Reputation: 66
I try to run the following. I was expecting the integer part (151511919299292911851) but I get a value of 151511919299292921856 that is -10005 less than what I expected.
import math
math.trunc(float('151511919299292911851.06'))
Upvotes: 0
Views: 381
Reputation: 32878
This is caused by the limited precision (usually 53 significant bits) supported by float
values. To avoid this, use the arbitrary-precision Fraction
class from Python's fractions
module:
In [32]: from fractions import Fraction
In [35]: import math
In [38]: math.trunc(Fraction('151511919299292911851.06'))
Out[38]: 151511919299292911851
In [39]: math.trunc(float('151511919299292911851.06'))
Out[39]: 151511919299292921856
In [40]: math.trunc(float('-151511919299292911851.06'))
Out[40]: -151511919299292921856
In [41]: math.trunc(Fraction('-151511919299292911851.06'))
Out[41]: -151511919299292911851
Upvotes: 3