Drawing Blanks

Premature Optimization is a Prerequisite for Success

Non-numbers

leave a comment »

Here is how double.IsNaN() implemented, it’s funny:

/// Returns a value indicating whether the specified 
/// number evaluates to a value that is not a number 
public static bool IsNaN(double d)
{
   return d != d;
}

The double type can get you in trouble because it can store things like NaN and Infinity. It will silently divide by zero, take square roots and logarithms of negatives, and keep calculating, and you will have a hard time finding out where exactly your math is failing. It gets particularly funny when your formulas are right, but because of loss of precision your value under Math.Acos() becomes slightly greater than 1…

Sometimes you’d get a number when you would expect a NaN, e.g.

Math.Pow(0, double.PositiveInfinity) //is zero and not NaN
Math.Pow(1, double.PositiveInfinity) //is one and not NaN

 

And there is no such thing as double.IsNumber(), so if you want to check whether your calculation succeeded you need to check .IsNaN() && .IsInfinity()

So it’s a lot of fun…

Advertisements

Written by bbzippo

07/19/2012 at 4:10 am

Posted in programming

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: