-3

So I was making a quadradic equation solver in Python and when the calculation was happening, an error came up and I'm not sure what is happening.

from math import sqrt

a = float(input("a: "))
b = float(input("b: "))
c = float(input("c: "))
Z = (b * b) - (4 * a * c)

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

print("x = " + str(x1))
print("x = " + str(x2))

This is the code.

Aidan
  • 23
  • 3
  • is it possible that `Z` is negative? You should get the square root of the absolute value, no? `sqrt(abs(Z))` – jkr May 16 '20 at 16:59
  • Taking the square root of the absolute value isn't a good idea: it would result in printing incorrect answers for quadratic equations that don't have any real solutions. – Mark Dickinson May 16 '20 at 17:27

1 Answers1

0

It's probably because if (4 * a * c) > (b * b), Z becomes negative and square root of a negative number results in an imaginary number. math.sqrt() doesn't take negative parameters. Edit: As @jakub said so, you can try getting the absolute value's square root.

Alper Berber
  • 71
  • 2
  • 10