Infinity, Epsilon and NaN

I inadvertently learned some new things about the .NET double struct while refactoring some code over the past couple of days.  A large set of test data we received recently revealed that we weren’t correctly handling the following edge cases of body mass index (BMI) calculation.

  • Edge case 1: a height of zero inches
  • Edge case 2: a weight of zero pounds and a height of zero inches
  • Edge case 3: a weight of zero pounds and a non-zero height

Incorrectly handling the first case resulted in an overflow exception in our code, but only because it tried to pass the result of a BMI calculation that returned the constant PositiveInfinity into another method.  To handle this condition more gracefully (since a height of zero inches and/or a weight of zero pounds are considered valid inputs), a check for PositiveInfinity is needed.  The .NET framework provides the static method IsPositiveInfinity for such comparisons.

Incorrect handling of the second case caused an error as well.  But this time the BMI calculation returned the constant NaN.  Like PositiveInfinity, NaN has a static method to check for it (IsNaN).

Enough time has gone by (and enough code changes have taken place) since I first started this post back in September that I don’t recall precisely what the original code did in the third case.  Under normal circumstances the BMI calculation would return zero, but our implementation returns the NaN constant if the BMI (or inputs to it) falls outside what are considered valid ranges.