Win a copy of Head First Android this week in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

Handling NaN.....

 
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Try something like

[ March 26, 2004: Message edited by: Jim Yingst ]
 
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic