pythonmathparametric-equations

Using If Statements To Check If Something Raises An Error


I'm trying to write a program that will solve questions about parametric equations for me. I'm trying to do the following:

I'm trying to find 2 answers to a parametric equation. The first answer will be the positive square root. The second answer will be the negative square root. If the first square root raises a math domain error, don't find the second answer. This is what I have so far:

def hitsGround(vertical_velocity, y_coordinate):
    h = vertical_velocity/-16/-2
    k = -16*(h)**2 + vertical_velocity*(h) + y_coordinate
    time = float(input("At what height do you want me to solve for time?: "))
    try:
        hits_height1 = math.sqrt((time - k)/-16) + h
    except ValueError:
        print("It won't reach this height.")
    else:
        print(f"It will take {hits_height1} seconds to hit said height.")

    try:
        hits_height2 = -math.sqrt((time - k)/16) + h
    except ValueError:
        print("There is no second time it will reach this height.")
    else:     
        print(f"It will take {hits_height2} seconds to hit said height.")

Is there any way to use an if statement to check if the first equation raises a math domain error so I can make it so it doesn't find the second answer? Thanks!


Solution

  • You cannot test for a run-time exception with if; that's exactly what try-except does. However, when the illegal operation is so directly defined, you can test for that condition before you try the sqrt opertaion:

    if (time - k)/-16 < 0:
        # no roots
    else:
        # proceed to find roots.