1

I have a code for a quadratic formula solver, but I can't get NaN to behave with my if statements.

package homework;
import java.util.Scanner;
import java.lang.Math;
//                          My Name 9/18/18 
// The purpose of this class is to allow a user to input an a,b, and c     value     and perform the quadratic equation on them
public class QuadFormHW 
{

public static void main(String[] args) 
{
    double a,b,c,answer1,answer2;
    Scanner inputReader = new Scanner(System.in);
    System.out.print("Please enter an \"a\" \"b\" and \"c\" value.");
    a = inputReader.nextDouble();
    b = inputReader.nextDouble();
    c = inputReader.nextDouble();
    answer1 = (-b + Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
    answer2 = (-b - Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
    if (answer1 == NaN)
    {
        System.out.print("Error cannot calculate");
    }
    else if (answer2 == NaN)
    {
        System.out.print("Error cannot calculate");
    }
    else
    {
        System.out.printf("Your answers are: %.3f , %.3f",answer1,answer2); 
    }
    inputReader.close();
}

}

Can anyone help me understand why NaN isn't a acceptable value?

phuclv
  • 37,963
  • 15
  • 156
  • 475
  • Use Float.NaN instead? – Mad Physicist Sep 19 '18 at 00:21
  • 1
    In this very specific case you can check for all places where a NaN would occur without ever performing the calculation: `Math.sqrt(x)` is NaN if `x < 0` and `x/y` is NaN if `y` is 0. Before you calculate do: `double toCheck = Math.pow(b, 2) - (4 * a * c); if(toCheck < 0 || a == 0) { /* would be NaN */ }` and only calculate the rest if neither of these would cause a NaN. – Johannes Sep 19 '18 at 00:28

1 Answers1

0

You're asking the same question as this older QA posting: How do you test to see if a double is equal to NaN? (I've marked this as a duplicate of that).

In short: By design, NaN cannot be meaningfully compared to any other value, (so foo == NaN won't work for your purposes). This is because of NaN-propagation.

Instead, to test for NaN, use Double.isNaN( value ) or Float.isNaN( value ).

Dai
  • 141,631
  • 28
  • 261
  • 374