Math Domain error in PYTHON

Asked

Viewed 6,760 times

0

I know that if the root is less than zero it will not exist, but, something happens, even if I implement that if the delta value is less than zero is to write the error it still continues showing "Math Domain error" I do not know the reason. I leave the code down here for 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")
  • Start by fixing the indentation so that you play 100% with the code as you have written it, as well as placing the Imports you are using

2 answers

1


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 may be negative, before checking whether it really is negative.

You have to first check if it is negative, and only if you are not trying 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")

1

I know this was a long time ago, but I am learning and Utlizei in 3.9 and had to change the (d) to (delta) and Math.sqrt(d) to sqrt(delta):

from math import sqrt

""" codigo original, tive que inserir valores para que sublimetext me deixe probar
a = int(input("Digite o valor de A: "))
b = int(input("Digite o valor de B: "))
c = int(input("Digite o valor de C: "))
"""

a = 2
b = 400
c = 6


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

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

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

elif delta < 0:
    print("Essa raiz é menor do que zero")

Browser other questions tagged

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