Search code examples
python-3.xmathwhile-loopdo-whileceil

Math.ceil(x) using while loop


Last time i was learning math module and I can not understand how math.ceil() works. I was trying to use it with while loop, but I do not know how exacly it works. Here is my little code:

import math

x = 20.4
y = 20.4

x = math.ceil(x)

while y != x:
    y += 0.1
    print(y)

It just can not stop calculating, why is that? It even prints numbers like 20152.599999987233 or higher.


Solution

  • Python has issues with comparing two floating point numbers, due to problems with precision/rounding. Python actually evaluates y to the closest approximation of 21.0 when you expect it to be 21. Due to this, they're not equal and the condition of y != x never evaluates to False, causing the infinite loop you're experiencing.

    You can use the math.isclose function instead of using equality to fix the issue:

    import math
    
    x = math.ceil(20.4)
    y = 20.4
    
    while not math.isclose(x,y):
        y += 0.1
        print(y)
    

    Now, your loop should terminate when y is "close to" 21 - this was my output:

    20.5
    20.6
    20.700000000000003
    20.800000000000004
    20.900000000000006
    21.000000000000007