Search code examples
pythonmatherror-handlingvalueerrorsqrt

How to fix 'ValueError: math domain error' in python?


I am trying to write a program which calculates formula y=√x*x + 3*x - 500, Interval is [x1;x2] and f.e x1=15, x2=25.

I tried to use Exception Handling but it didn't help. And the code I try to use now gives me: ValueError: math domain error

import math

x1 = int(input("Enter first number:"))
x2 = int(input("Enter second number:"))
print(" x", "   y")
for x in range(x1, x2):
    formula = math.sqrt(x * x + 3 * x - 500)
    if formula < 0:
        print("square root cant be negative")
    print(x, round(formula, 2))

The output should look like this:

x   y
15 ***
16 ***
17 ***
18 ***
19 ***
20 ***
21 2.00
22 7.07
23 9.90
24 12.17
25 14.14

Solution

  • The argument of square root mustn't be negative. It's perfectly fine to use exception handling here, see below:

    Playground: https://ideone.com/vMcewP

    import math
    
    
    x1 = int(input("Enter first number:\n"))
    x2 = int(input("Enter second number:\n"))
    
    print(" x\ty")
    for x in range(x1, x2 + 1):
        try:
            formula = math.sqrt(x**2 + 3*x - 500)
            print("%d\t%.2f" % (x, formula))
        except ValueError:  # Square root of a negative number.
            print("%d\txxx" % x)
    
    

    Resources: