programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Handling NaN.....

Will Carpenter
Greenhorn
Posts: 26
Given the following:
public class TrivialApplication
{ public static void main(String args[])
{
double A = 16, B = 5, C = 9;
double num;
num = ( -B + Math.sqrt( (B*B) - (4*A*C) ) ) / (2*A);
System.out.println(num);
num = ( -B - Math.sqrt( (B*B) - (4*A*C) ) ) / (2*A);
System.out.println(num);

}
}
Of course, when I run the above the displays say NaN. (Not a number, because you can't use Math.sqrt to find the root of a negative number.)
What'd I'd like to do is say "If num is NaN, move 0 to num", but how do I use NaN in an expression?

Jim Yingst
Wanderer
Sheriff
Posts: 18671
Try something like

[ March 26, 2004: Message edited by: Jim Yingst ]

Ben Buchli
Ranch Hand
Posts: 83
Hey, looks like an assignment I once had.
Why dont you just check the discriminant and if its less than zero you will have to create an imaginary number. I dont know however if you are required to do that (it's not a biggie though).
discriminant: ( bx * bx ) - ( 4 * ax * c )
so if you want to assign zero (is that what you mean by "move zero to num" ?) instead of creating an imaginary number, try something like this:
public class TrivialApplication
{ public static void main(String args[])
{
double A = 16, B = 5, C = 9;
double num;
//added this part to your code: check whether discr. is neg. nbr
//if so, execute following code, otherwise go to "else"
if ( ( B * B ) - ( 4 * A * C ) < 0 )
{
num = ( -B + Math.sqrt( (B*B) - (4*A*C) ) ) / (2*A);
System.out.println(num);
num = ( -B - Math.sqrt( (B*B) - (4*A*C) ) ) / (2*A);
System.out.println(num);
} else
num = 0;
}
}
[ March 27, 2004: Message edited by: Ben Buchli ]
[ March 28, 2004: Message edited by: Ben Buchli ]

 It is sorta covered in the JavaRanch Style Guide.