2

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?

gustabtc
  • 25
  • 3
  • 1
    ``X`` *isn't* less than ``Y``. You are explicitly using base-2 64-bit floating point numbers (aka ``float``), for which ``2.50000000000000001`` is *exactly* equal to ``2.5``. – MisterMiyagi Mar 22 '21 at 11:30
  • 2
    Does this answer your question? [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – MisterMiyagi Mar 22 '21 at 11:31
  • 1
    Does this answer your question? [Is floating point arbitrary precision available?](https://stackoverflow.com/questions/11522933/is-floating-point-arbitrary-precision-available) – MisterMiyagi Mar 22 '21 at 11:37
  • Simply doing `y = float("2.50000000000000001")` and then `print(y)` will reveal to you that `y` is literally `2.5`... – Tomerikoo Mar 22 '21 at 12:10

1 Answers1

2

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.

Harry
  • 1,105
  • 8
  • 20