C# Doubles and Divide By Zero (0) Gives no Exception

In a recent project there were several methods which performed various mathematical  calculations. One such method took in Doubles as parameters and performed several divides. According to the manner in which the method was written a Divide by Zero exception was to be caught if one of the doubles passed in was Zero. Unfortunately, no such exception was ever caught and strange results were being returned by the method thus corrupting the results of all calculations which called that method.

After some research I found out why. In C# Doubles are a form of Floating Point number, this means that they are to be used for scientific calculations and have been designed to never throw an exception because Zero is not their limit. According to the .Net documentation Doubles have a range supporting values from negative 1.79769313486232e308 to positive 1.79769313486232e308., this gives each Double a precision of ~29 digits. Because of this as the number approaches 0 it reaches a level of precision which is considered by the .net compiler as infinity and the results returned are either ‘Positive Infinity’ or ‘Negative Infinity’. Because Doubles are meant for Floating Point precision in scientific calculations you may need to select a less precise variable type to perform your calculations.

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s