This week's book giveaway is in the Java in General forum.
We're giving away four copies of Think Java: How to Think Like a Computer Scientist and have Allen B. Downey & Chris Mayfield on-line!
See this thread for details.
Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Handling NaN.....

 
Will Carpenter
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try something like

[ March 26, 2004: Message edited by: Jim Yingst ]
 
Ben Buchli
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic