Search code examples
pythonfloating-pointinfinite-loop

infinite while loop although I put break statement


this code is supposed to take slope (m) and y-intercept (b) of two lines and checks if these two line hit each other or not. the problem is my while loop is infinite although I have condition and break statement

print("enter the first m: ")
m = input()  # m = slope

print("enter the first b: ")
b = input()  # b = y-intercept

print("enter the second m: ")
m1 = input()

print("enter the second b: ")
b1 = input()

sub_m = int(m) - int(m1) #sub = subtract
sub_b = int(b) - int(b1)

if (sub_m == 0):
    print("parallel")

x = float(-sub_b / sub_m)
r = round(x, 1)

i = 0.0
while i != r:

    print(r, i)
    if (i == r):
        print("\nhit piont: ", i)
        break

    if (sub_m > 0 and sub_b > 0):
        i -= 0.1
    elif (sub_m < 0 and sub_b < 0):
        i -= 0.1
    else:
        i += 0.1

Solution

  • Running this in my debugger showed that you're getting floating point representation errors. This means that although technically you should be getting numbers perfectly rounded to 1 decimal given that you're applying increments of 0.1, in reality this isn't the case:

    enter image description here

    As you can see, r = -2.0 and i = -2.00...4, thus at no point is r == i.

    You can fix this by adding another round statement at the end:

    print("enter the first m: ")
    m = input()  # m = slope
    
    print("enter the first b: ")
    b = input()  # b = y-intercept
    
    print("enter the second m: ")
    m1 = input()
    
    print("enter the second b: ")
    b1 = input()
    
    sub_m = int(m) - int(m1) #sub = subtract
    sub_b = int(b) - int(b1)
    
    if (sub_m == 0):
        print("parallel")
    
    x = float(-sub_b / sub_m)
    r = round(x, 1)
    
    i = 0.0
    while i != r:
    
        print(r, i)
    
        if (sub_m > 0 and sub_b > 0):
            i -= 0.1
        elif (sub_m < 0 and sub_b < 0):
            i -= 0.1
        else:
            i += 0.1
        i = round(i, 1)  # <- this
    
    print(f"Hit pt: {i}")
    

    HOWEVER: This is still error prone, and I recommend finding a way to avoid if i==r altogether in the code. If i is lower than r, exit the loop when it finally becomes bigger, and viceversa. Its best practice to avoid using the == condition when comparing floats, and to find a way to use <= and >=.