In Python, please note, 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 is 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}.
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)
Below, I have also altered the below code in the favor of pythonic programming, since NumPy helps us to find the roots of polynomial equations with prowess.
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)
Interested to learn more about python, Come and Join: Python online course