math domain error in PYTHON

0

I know that if the root is less than zero it will not exist, but, something happens, even though I implement that if the delta value is less than zero it is to write the error it still continues showing "math domain error "I do not know the reason. I leave the code below for a better judgment.

a = float(input("Insira um valor para A: "))

b = float(input("Insira um valor para B: "))

c = float(input("Insira um valor para C: "))



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

print("Delta: ",d)

delta = math.sqrt(d)

print("Raiz quadrada de delta: ",delta)



if d > 0:

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

x2 = (-b - delta)/ (2*a)

print("X1 = ", x1, "X2 = ", x2)

elif d == 0:

x = -b / (2*a)

print("Valor de x = ",x)

elif d < 0:

print("Essa raiz é menor do que zero")
    
asked by anonymous 01.05.2018 / 23:48

1 answer

0

The error happens exactly on this line:

delta = math.sqrt(d)

And it happens because you tell him to calculate the square root of d , which can be negative, before verifying that it really is negative.

You have to first check if it is negative, and only if you do not try to calculate the root:

import math

a = float(input("Insira um valor para A: "))
b = float(input("Insira um valor para B: "))
c = float(input("Insira um valor para C: "))

d = b ** 2 - 4 * a * c
print("Delta: ", d)


if d > 0:
    delta = math.sqrt(d)
    print("Raiz quadrada de delta: ", delta)
    x1 = (-b + delta) / (2 * a)
    x2 = (-b - delta) / (2 * a)
    print("X1 = ", x1, "X2 = ", x2)

elif d == 0:
    delta = math.sqrt(d)
    print("Raiz quadrada de delta: ", delta)
    x = -b / (2 * a)
    print("Valor de x = ", x)

elif d < 0:
    print("Essa raiz é menor do que zero")
    
02.05.2018 / 00:22