Python Quadratic Equation
The quadratic equation has the form:ax2+bx+c=0。
Its solution can be found by evaluating the discriminantto determine:
- If, the equation has two real roots.
- If, the equation has one real root (a double root).
- If, the equation has no real roots, but has two complex roots.
The following example takes user input numbers and calculates the quadratic equation:
Example (Python 3.0+)
# Filename: quadratic_solver.py
# Author: www.example.com (optimized by ChatGPT)
# Program function: Solve the quadratic equation ax**2 + bx + c = 0
# Note: a ≠ 0, a, b, c are real numbers entered by the user
import cmath # Import the cmath module to support complex number operations
def get_float_input(prompt):
"""Get a floating-point number entered by the user, and handle invalid input.
:param prompt: Prompt message
:return: The floating-point number entered by the user"""
while True:
try:
return float(input(prompt))
except ValueError:
print("Please enter a valid number!")
def solve_quadratic(a, b, c):
"""Calculate the solutions of the quadratic equation.
:param a: Coefficient of the quadratic term
:param b: Coefficient of the linear term
:param c: Constant term
:return: The two solutions of the quadratic equation"""
discriminant = b**2 - 4*a*c # Calculate the discriminant
root1 = (-b - cmath.sqrt(discriminant)) / (2 * a)
root2 = (-b + cmath.sqrt(discriminant)) / (2 * a)
return root1, root2
def main():
print("Solve the quadratic equation ax^2 + bx + c = 0")
# Get user input
a = get_float_input("Please enter the coefficient of the quadratic term a (a ≠ 0):")
while a == 0:
print("The coefficient a of the quadratic term cannot be 0!")
a = get_float_input("Please re-enter the coefficient of the quadratic term a (a ≠ 0):")
b = get_float_input("Please enter the coefficient of the linear term b:")
c = get_float_input("Please enter the constant term c:")
# Calculate and output the result
root1, root2 = solve_quadratic(a, b, c)
print(f"The solutions of the equation are: {root1} and {root2}")
if __name__ == "__main__":
main()
The output after running the above code is:
求解二次方程 ax^2 + bx + c = 0 请输入二次项系数 a(a ≠ 0):1 请输入一次项系数 b:5 请输入常数项 c:6 方程的解为:(-3+0j) 和 (-2+0j)
In this example, we used the sqrt() method of the cmath (complex math) module to calculate the square root.
Example 2
import math
import cmath
def solve_quadratic(a, b, c):
"""
Solve the quadratic equation ax^2 + bx + c = 0
:param a: Coefficient of the quadratic term
:param b: Coefficient of the linear term
:param c: Constant term
:return: The solutions of the equation (may be real or complex)
"""
if a == 0:
# Handle non-quadratic equations
if b == 0:
return "No solution" if c != 0 else "The equation has infinitely many solutions"
return f"The equation is linear, and the solution is x = {-c / b}"
# Calculate the discriminant
delta = b**2 - 4*a*c
if delta > 0:
# Two real roots
root1 = (-b + math.sqrt(delta)) / (2 * a)
root2 = (-b - math.sqrt(delta)) / (2 * a)
return f"The equation has two real roots: x1 = {root1}, x2 = {root2}"
elif delta == 0:
# One real root
root = -b / (2 * a)
return f"The equation has a double real root: x = {root}"
else:
# Two complex roots
root1 = (-b + cmath.sqrt(delta)) / (2 * a)
root2 = (-b - cmath.sqrt(delta)) / (2 * a)
return f"The equation has two complex roots: x1 = {root1}, x2 = {root2}"
# Example call
a, b, c = 1, -3, 2
result = solve_quadratic(a, b, c)
print(result)
import cmath
def solve_quadratic(a, b, c):
"""
Solve the quadratic equation ax^2 + bx + c = 0
:param a: Coefficient of the quadratic term
:param b: Coefficient of the linear term
:param c: Constant term
:return: The solutions of the equation (may be real or complex)
"""
if a == 0:
# Handle non-quadratic equations
if b == 0:
return "No solution" if c != 0 else "The equation has infinitely many solutions"
return f"The equation is linear, and the solution is x = {-c / b}"
# Calculate the discriminant
delta = b**2 - 4*a*c
if delta > 0:
# Two real roots
root1 = (-b + math.sqrt(delta)) / (2 * a)
root2 = (-b - math.sqrt(delta)) / (2 * a)
return f"The equation has two real roots: x1 = {root1}, x2 = {root2}"
elif delta == 0:
# One real root
root = -b / (2 * a)
return f"The equation has a double real root: x = {root}"
else:
# Two complex roots
root1 = (-b + cmath.sqrt(delta)) / (2 * a)
root2 = (-b - cmath.sqrt(delta)) / (2 * a)
return f"The equation has two complex roots: x1 = {root1}, x2 = {root2}"
# Example call
a, b, c = 1, -3, 2
result = solve_quadratic(a, b, c)
print(result)
Python3 Examples