Valueerror: Math Domain error

Asked

Viewed 503 times

0

Can anyone help me with the error below: Sometimes it appears sometimes not , I am Noob and I do not understand why this.

Code:

import math

a = float(input("digite o valor de a: "))
b = float(input("digite o valor de b: "))
c = float(input("digite o valor de c: "))

delta = b**2 - 4 *a*c
raiz_delta = math.sqrt(delta)

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

print("x1 e igual a ", x1)
print("x1 e igual a ", x2)

Error:

digite o valor de a: >? 2
digite o valor de b: >? 5
digite o valor de c: >? 6
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.3\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.3\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/Users/DACIO/PycharmProjects/Introducao_ao_Python_Diego_Mariano/Respostas_Curso_V2.py", line 34, in <module>
    raiz_delta = math.sqrt(delta)
ValueError: math domain error
  • This error is due to the value of delta is negative and it is not possible to take the square root of a negative number.

1 answer

1

Well, as commented by another user, the function math.sqrtis only set to positive numbers and therefore returns an error every time delta is negative. There are two solutions to your problem. The first is to take advantage of your code and include a conditional. See:

import math

a = float(input("digite o valor de a: "))
b = float(input("digite o valor de b: "))
c = float(input("digite o valor de c: "))

delta = b**2 - 4 *a*c

if delta>0:
    raiz_delta = math.sqrt(delta)

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

    print("x1 e igual a ", x1)
    print("x1 e igual a ", x2)
else:
    print('Delta tem valor negativo e, portanto, as raízes da equação são números complexos')

The second option is to use the built-in function pow whose domain includes negative numbers.

a = float(input("digite o valor de a: "))
b = float(input("digite o valor de b: "))
c = float(input("digite o valor de c: "))

delta = b**2 - 4 *a*c

print(delta)
raiz_delta = pow(delta,0.5)

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

print("x1 e igual a ", x1)
print("x1 e igual a ", x2)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.