Saeid Mohammadi Nejati
Saeid Mohammadi Nejati

Reputation: 521

Changing order of numbers in a simple math operation yields different result?

print((1199/1070)*1070)

returns: 1198.9999999999998

print((1070/1070)*1199)

returns 1199.0

how to overcome this behavior ? ( Python version == 3.8.3 )

Upvotes: 0

Views: 113

Answers (1)

Oli
Oli

Reputation: 2602

This is caused by floating point numbers being in binary, making fractions with a denominator of anything other than a power of 2 only approximate.

To fix this, you can use the built-in fractions library: https://docs.python.org/3/library/fractions.html

from fractions import Fraction

print(float(Fraction(1199)/1070*1070)) # prints: 1199.0
print(float(Fraction(1070)/1070*1199)) # prints: 1199.0

This will be slower than floating point operations, but will not have any errors from numbers that are unrepresentable in binary floating point in a finite amount of space.

Upvotes: 2

Related Questions