Skip to content Skip to sidebar Skip to footer

Why Math.trunc Do Not Work As Expected In Python?

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 mat

Solution 1:

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

Post a Comment for "Why Math.trunc Do Not Work As Expected In Python?"