In python x ^ 2, can be x ** 2, x * x or pow(x, 2).
Others have given you good suggestions, and I would like to add a few.
The Quadratic Equation: ax^2 + bx + c = 0 (Adjust to make the equation equal zero!)
has polynomial terms ax^2, bx, c; whose coefficients are a, b. And c being the constant term.
then the Quadratic formulae: (-b + sqrt(b ^ 2 - 4 * a * c)) / 2a; Solves for x.
All of the above appears rightly in your code
However, you will have trouble if the solutions dwell in complex numbers set {C}.
This can be easily tackled by gauging the "discriminant".
The discriminant is b^2 - 4ac, and
- if discriminant = 0, then there is only one solution
- if discriminant > 0, then there are two real solutions
- if discriminant < 0, then there are two complex solutions
Considering above conditions, the code should look so:
import math
print ("Quadratic Equation Calculator")
a = float(input("Enter the coefficient of term `x ^ 2` (degree 2), [a]: "))
b = float(input("Enter the coefficient of term `x` (degree 1), [b]: "))
c = float(input("Enter the constant term (degree 0), [c]: "))
discriminant = pow(b, 2) - 4.0 * a * c
if discriminant == 0:
root1 = root2 = (-1 * b) / (2 * a)
elif discriminant < 0:
root1 = ((-1 * b) - math.sqrt(-discriminant) * 1j) / (2 * a)
root2 = ((-1 * b) + math.sqrt(-discriminant) * 1j) / (2 * a)
else:
root1 = ((-1 * b) - math.sqrt(discriminant)) / (2 * a)
root2 = ((-1 * b) + math.sqrt(discriminant)) / (2 * a)
print (root1)
print (root2)
Similar SO answers: https://stackoverflow.com/a/49837323/8247412
Below I have altered the code in favour of pythonic programming, as numpy can find roots of polynomial (quadratic and higher order) equations with prowess.
numpy.roots
import numpy as np
print ("Quadratic Equation Calculator")
a = float(input("Enter the coefficient of term `x ^ 2` (degree 2), [a]: "))
b = float(input("Enter the coefficient of term `x` (degree 1), [b]: "))
c = float(input("Enter the constant term (degree 0), [c]: "))
coeffs = [a, b, c] # or d, e and so on..
roots = np.roots(coeffs)
print (roots)