How to make Python stop rounding very close numbers?

Viewed 152

I've made this algorithm to test how python compares close numbers

x = 2.5                                # arbitrary number chosen to do the testing
y = float(input('Insert Y '))        # 
print('X > Y = {}'.format(x > y))      # shows whether x>y
print('X = Y = {}'.format(x == y))     # shows whether x = y
print('X < Y = {}'.format(x < y))      # shows whether x < y

For y = 2.50000000000000001, which has the minimum amount decimal places for Python to automatically round the number. Execution:

Insert Y 2.50000000000000001
X > Y = False
X = Y = True
X < Y = False

Process finished with exit code 0

How to make Python realise X is less than Y, not rounding it?

1 Answers

Real numbers (e.g. 2.5) are represented in the float number format in Python. A float number is represented as sign * mantissa * 2^exponent, e.g. 3.0=1.5*2^1. Each of the parts (sign, mantissa, exponent) is stored as an integer.

Now, to represent your number 2.50000000000000001, you would need to store the integer 250000000000000001, which needs ceil(log2(250000000000000001))=58bit. But for float64 (which is almost always used in Python), the mantissa is 52bit large, which is too small to hold this number.

When reading an input into float representation, rounding takes place to get the closest number possible to your input. This is why X and Y are equal in your example.

Related