Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve imaginary quadratic roots in java?

Tags:

java

I've been trying a lot but it only shows NaN. I'm not sure if I'm doing the right thing.

 class Imaginary{
    
     double a = 2;
     double b = 3;
     double c = 5;
     double result = b * b - 4 * a * c;
    
     if(result < 0.0){
      double im1 = -2 + (Math.sqrt((result))/ 10);
      double im2 = -2 - (Math.sqrt((result))/ 10);
    
    
      System.out.println("x = " + imaginary1 + " or x = " + imaginary2);
            }
 }
like image 971
Jeyz Avatar asked Mar 29 '26 19:03

Jeyz


2 Answers

You need to take negate result to make it positive before taking the square root (taking square roots of negative numbers always results in NaN) and append "i" before printing.

double real = -b / (2*a);
double img = Math.sqrt(-result) / (2*a);
System.out.println("x = " + real + " + " + img +"i or x = " + real + " - " + img + "i");
like image 67
Unmitigated Avatar answered Apr 01 '26 08:04

Unmitigated


You shouldn't use sqrt(result) since it will always result in you taking the square root of a negative number (that is your condition for result). Instead try to use a formula (eg completing the square).

Hope it answers your question :)

like image 29
The dickmaster Avatar answered Apr 01 '26 06:04

The dickmaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!