In previous lab exercises, you have written programs to solve the quadratic equation assuming the solution is real. We will now think about how to solve the equation in the more general case where possibly \( B^2 - 4AC \lt 0 \). In this case, no real values of \( x \) can solve the equation. Instead we need to use complex numbers, which is a number of the form \( a + bi \), where \( i = \sqrt{-1} \). Here, \( i \) is known as an imaginary number.
Note that the square root of a negative number can be written as \( i \) times the square root of the corresponding positive number:
\[ \sqrt{-4} = \sqrt{4 \times -1} = \sqrt{4} \times \sqrt{-1} = 2i\\ \sqrt{-9} = \sqrt{9 \times -1} = \sqrt{9} \times \sqrt{-1} = 3i \]Returning to the quadratic equation:
\[ x = \frac{-B \pm \sqrt{B^2 - 4AC} }{2A} = \frac{-B}{2A} \pm \frac{ \sqrt{B^2 - 4AC}}{2A} \]The term \( B^2 -4AC \) is known as the discriminant.
- If the discriminant is positive, the solution will be a real number (as in a previous exercise).
- If the discriminant is negative, then the solution will be a complex number.
To calculate the complex solution, we can rewrite the equation as:
\[ x = \frac{-B \pm \sqrt{B^2 - 4AC} }{2A} = \frac{-B}{2A} \pm \frac{ \sqrt{ abs(\mathit{discriminant}) \times -1}}{2A} \]and so
\[ \begin{split}x &= \frac{-B \pm \sqrt{B^2 - 4AC} }{2A} = \frac{-B}{2A} \pm \frac{ \sqrt{ abs(discriminant)} \times i}{2A}\end{split} \]where abs() is a function that returns the absolute value of a number. This allows you to calculate the imaginary component of the solution.
Write a program ImQuadraticSolver which solves quadratic equations in the general case, when the solutions can be complex. For example, your program should produce the following output:
: java ImQuadraticSolver 1.0 0.0 -1.0 1.0 -1.0 : java ImQuadraticSolver 1.0 -3.0 2.0 2.0 1.0 : java ImQuadraticSolver 1.0 -2.0 2.0 1.0 + 1.0i 1.0 - 1.0i
You will need to calculate the ‘discriminant’, and depending on whether it is positive or negative, derive the real and imaginary parts of the solutions in slightly different ways. It is easiest to start with the case when the discriminant is positive, as this will always produce real solutions.
Note
In the case of a non-real solution, it may help to create additional variables to hold the real and imaginary parts of the solution.
Improve your program ImQuadraticSolver so that it can handle the case where \( A = 0 \). It is still possible to solve some equations even if \( A = 0 \), although there will now be just a single solution. To see this, we can rearrange the original equation we are trying to solve in the following way:
\[ Ax^2 + Bx + C = 0 \]In the case that \( A = 0 \),
\[ Bx + C = 0\\ x = \frac{-C}{B} \]Your program should test for this case; and if it holds, then print out the single solution.
: java ImQuadraticSolver 0.0 1.0 1.0 -1.0
An automated test has been created for this exercise: ImQuadraticSolverTest.java.