[Python] How to fix 'ValueError: math domain error' for square root?

Discussão em 'Python' iniciado por Stack, Março 17, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to write a program that 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

    Continue reading...

Compartilhe esta Página