0

So, I wrote a Java program that finds the solutions to a quadratic equation and my problem is I can't seem to write the right code to find the "imaginary numbers" when it prints out I just get "NaN". Any solutions?

import java.util.Scanner;
class Main {
  public static void main(String[] args) {
    
    Scanner scan = new Scanner(System.in);
    
    System.out.print("Enter the value for a: ");
    double a = scan.nextDouble();
    
    System.out.print("Enter the value for b: ");
    double b = scan.nextDouble();
    
    System.out.print("Enter the value for c: ");
    double c = scan.nextDouble();
    
    double result = b * b - 4.0 * a * c;
    
    if(result > 0.0){

      //to find two real solutions

      double x1 = (-b + Math.pow(result, 0.5)) / (2.0 * a);
      double x2 = (-b - Math.pow(result, 0.5)) / (2.0 * a);
      
      System.out.println("There are two real solutions.");
      System.out.println("x1 = " + x1);
      System.out.println("x2 = " + x2);
      
      //to find one real solution

    } else if(result == 0.0){
      double x1 = (-b / (2.0 * a));
      System.out.println("There is one real solution");
      System.out.println("x = " + x1);

      //to find the imaginary numbers

    } else if(result < 0.0){
      double x1 = (-b + Math.pow(result, 0.5)) / (2.0 * a);
      double x2 = (-b - Math.pow(result, 0.5)) / (2.0 * a);
      
      System.out.println("There are two imaginary solutions.");
      System.out.println("x1  = " + x1 + " + " + x2);
      System.out.println("x2  = " + x1 + " - " + x2);
    }
    
  }
}
thomas
  • 19
  • 1
  • 2
    can you add an example you tested and expected output – deadshot Jul 13 '20 at 18:02
  • It’s not necessary to raise `results` to the 0.5 power, by the way. There is a [Math.sqrt](https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/Math.html#sqrt(double)) method. – VGR Jul 13 '20 at 19:01

1 Answers1

2

There are a couple of incorrect things in your code when handling complex roots (when result < 0):

  1. You are attempting to evaluate the square root of result which is negative. This is will result in a NaN. The correct approach is to get the square root of -result to get your answer.
  2. The way you are calculating the roots is incorrect. Both roots will have the same real part which is -b/(2*a) and the same value for imaginary part, differing only in its sign.

I fixed your code below to give a correct output. The real part is calculated and then the imaginary part is calculated. Roots are then printed with the imaginary parts suffixed with an 'i' to denote the imaginary part.

double real = -b / (2*a);
double imag = Math.pow(-result, 0.5) / (2.0 * a);

System.out.println("There are two imaginary solutions.");
System.out.println("x1  = " + real + " + " + imag + "i");
System.out.println("x2  = " + real + " - " + imag + "i");
Khaled Barie
  • 116
  • 5