In this blog post, I will be showing you how to create a python function that will solve any quadratic equation.
Firstly, what is a quadratic equation?
A quadratic is an algebraic equation that can be arranged as ax2 + bx + c = 0 where a, b, c are known and a ≠ 0. If a = 0 then the equation becomes linear as there isn’t a x2 term.
Secondly, how to solve this equation? There are different ways to solves quadratic equations including:
- By inspection
- Completing the square
- Quadratic formula
We will be using the quadratic formula which is:
We use the Quadratic formula because it can be used in any situation and there is no nuance to it like the other methods.
The first part of the code is to define a function that will accept 3 parameters: a, b & c
To use the quadratic formula, we will use the square root function from the imported math module.
Before plugging the parameters into the formula, we can work out how many real roots we will get by using the discriminant. The discriminant is b2 – 4ac.
If b2 – 4ac > 0 then there are 2 real roots.
If b2 – 4ac = 0 then there is 1 real root.
If b2 – 4ac < 0 then there are no real roots. (There are complex roots using imaginary numbers, but we won’t go into that here, maybe in a part 2)
Let’s add calculating the discriminant and an IF statement depending on the result to the function.
Next, lets plug a, b & c into the quadratic formula.
When the discriminant = 0 we only need to find the value of root1 as it’s equal to root2. Knowing the discriminant = 0, we could simplify the equation to
In the code I have chosen to leave the full formula in.
That’s our code complete, finally let’s test the function with the 3 different discriminant scenarios.
The function works as intended, the code is attached as a txt file.