Python Solve Quadratic Equation
Given a quadratic equation the task is solve the equation or find out the roots of the equation. Standard form of quadratic equation is $$ax^2+ bx + c =0$$ where, $a, b$, and $c$ are coefficient and real numbers and also $a \ne 0$ 0. If $a$ is equal to $0$ that equation is not valid quadratic equation.
See more: Hướng dẫn lập trình Python – Python Guide
1. Python Solve Quadratic Equation Using the Direct Formula
Using the below quadratic formula we can find the root of the quadratic equation.
Let $\Delta =b^2-4ac$, then:
- If $b^2 – 4ac<0$, then roots are complex (not real).
- If $b^2 – 4ac=0$, then roots are real and both roots are same $x=\frac{-b}{2a}$.
- If $b^2 – 4ac>0$, then roots are real and different $$ x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}.$$
# Python program to find roots of quadratic equation import math # function for finding roots def equationroots(): a = float(input('Enter coefficient a: ')) while a == 0: print("Coefficient a can not equal 0") a = float(input('Enter coefficient a: ')) b = float(input('Enter coefficient b: ')) c = float(input('Enter coefficient c: ')) # calculating dcriminant using formula d = b * b - 4 * a * c # checking condition for dcriminant if d > 0: print("Your equation has real and different roots:") print((-b + math.sqrt(d))/(2 * a)) print((-b - math.sqrt(d))/(2 * a)) elif d == 0: print("Your equation has real and same roots:") print(-b / (2 * a)) # when dcriminant is less than 0 else: print("Your equation has complex roots:") print(- b / (2 * a), " +", math.sqrt(-d),'i') print(- b / (2 * a), " -", math.sqrt(-d),'i') equationroots()
2. Python Solve Quadratic Equation Using the Complex Math Module
First, we have to calculate the discriminant and then find two solution of quadratic equation using cmath
module.
cmath
module — Mathematical functions for complex numbers — provides access to mathematical functions for complex numbers. The functions in this module accept integers, floating-point numbers or complex numbers as arguments. They will also accept any Python object that has eithera __complex__()
ora __float__()
method: these methods are used to convert the object to a complex or floating-point number, respectively, and the function is then applied to the result of the conversion.
# Python program to find roots of quadratic equation import cmath # function for finding roots def equationroots(): a = float(input('Enter coefficient a: ')) while a == 0: print("Coefficient a can not equal 0") a = float(input('Enter coefficient a: ')) b = float(input('Enter coefficient b: ')) c = float(input('Enter coefficient c: ')) # calculating dcriminant using formula d = b * b - 4 * a * c if d == 0: print("Your equation has real and same roots:") print(-b / (2 * a)) # when dcriminant is not equal 0 else: print("Your equation has complex roots:") print(- b / (2 * a), " +", cmath.sqrt(d)) print(- b / (2 * a), " -", cmath.sqrt(d)) equationroots() input()