Its very well known due to the nature of floating point numbers .
If you want to do decimal arithmetic, floating point arithmetic, to do this.
eg.
>>> from decimal import Decimal >>> Decimal(29)/Decimal(100) Decimal('0.29') >>> Decimal('0.29')*100 Decimal('29') >>> int(Decimal('29')) 29
In the general case, the decimal number probably goes overboard and will still have rounding errors in rare cases when the number does not have a finite decimal representation (for example, any fraction where the denominator is not equal to 1 or divisible by 2 or 5 - decimal base factors (10)). For example:
>>> s = Decimal(7) >>> Decimal(1)/s/s/s/s/s/s/s*s*s*s*s*s*s*s Decimal('0.9999999999999999999999999996') >>> int(Decimal('0.9999999999999999999999999996')) 0
So it's best to always round before you float in ints if you don't want to use the floor function.
>>> int(1.9999) 1 >>> int(round(1.999)) 2
Another alternative is to use the fraction class from the fractions library, which doesn't come close. (He simply continues to add / subtract and multiply the numerators and denominators as necessary).
dr jimbob May 13 '11 at 19:57 2011-05-13 19:57
source share