wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Handling NaN..... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Handling NaN....." Watch "Handling NaN....." New topic
Author

Handling NaN.....

Will Carpenter
Greenhorn

Joined: Mar 17, 2004
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);

}
}
The good ole quadratic formula!
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

Joined: Jan 30, 2000
Posts: 18671
Try something like

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

"I'm not back." - Bill Harding, Twister
Ben Buchli
Ranch Hand

Joined: Mar 26, 2004
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 ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Handling NaN.....