简体   繁体   中英

math domain error python for quadratic equation

I'm a complete beginner and for some reason when I try to run the code it says that there's a math domain error. I don't really understand what the problem is, help would be greatly appreciated:)

a = float(input('Rentrer la valeur de a : '))
b = float(input('Rentrer la valuer de b : '))
c = float(input('Rentrer la valuer de c : '))
delta = b**2 - 4*a*c

x1 = ((-b) + sqrt(delta)) / (2*a)
x2 = ((-b) - sqrt(delta)) / (2*a)

console:

Traceback (most recent call last):
  File "main.py", line 31, in <module>
    x1 = ((-b) + sqrt(delta)) / (2*a)
ValueError: math domain error

The sqrt function must take as a parameter a positive number . When you enter the number a , b , and c you must make sure that the delta (discriminant) value is positive (see https://en.wikipedia.org/wiki/Discriminant https://www.expii.com/t/the-discriminant-of-a-quadratic-4540 ). If you enter the values a=1, b=3, c=-2 you won't see this error, since in this case the delta value is 17 (a positive number)

If you know what complex numbers are, you can use the sqrt function from the cmath package instead (from cmath import sqrt) and avoid this error, but you would be working with complex numbers.

The answer is quite surprisingly easy: you need the math lib:


from math import sqrt

a = float(input('Rentrer la valeur de a : '))
b = float(input('Rentrer la valuer de b : '))
c = float(input('Rentrer la valuer de c : '))
delta = b**2 - 4*a*c

x1 = ((-b) + sqrt(delta)) / (2*a)
x2 = ((-b) - sqrt(delta)) / (2*a)

print(x1, x2)

"""

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM