I have made a program for 2nd degree equations:
import math
print()
print("****Fórmula para ecuación de 2º Grado****")
print()
a = int(input("Introduzca primer miembro ="))
b = int(input("Introduzca segundo miembro ="))
c = int(input("Introduzca tercer miembro ="))
y = b ** 2 - 4 * a * c
math.sqrt(y)
r = math.sqrt(b ** 2 - 4 * a * c)
print(r)
x = (-b + r) / (2 * a)
print(x)
pause = input()
However, I get this error:
error: Traceback (most recent call last): File "C:/Users/USUARIO/PycharmProjects/PY1/Ecuacion.py", line 9, in <module>
math.sqrt(y) ValueError: math domain error
What is the mistake I am making?
The function
math.sqrt()
only works for positive arguments.You can check in your code if it
y
is positive before trying to compute the root. If it is not, the equation has no real solutions:Another possibility is to use the module
cmath
instead ofmath
. This module allows calculations with complex numbers, so even if there is no real solution to the equation, you could obtain its complex solution:This method, on the other hand, is "ugly" if the solution is real, since in any case it will show it to you as complex (although with the imaginary part equal to 0).
An additional detail, I would use
float(input(...))
instead ofint(input(...))
, because why do the coefficients of the equation have to be integers?If I remember correctly, the quadratic formula only returns a real value when the inner part of the square root is positive.
I don't know what values you are trying, but the error is because
is evaluating a negative number. Look for an example on the internet already done and you will see that it works well.
An alternative is to use a
try
to be prepared for these errors