Why should we be concerned about floating point arithmetic.

By Mirek on (tags: decimal, double, flaoating-point, categories: architecture)

This is often quite obvious that when we are developing application which operates on a real numbers we use a double data type in .net. Here you will see why you should take a special care about the floating point calculations in your software.

Generally all floating point calculation problems comes from the fact that many real number does not have an exact representation in floating point arithmetic. For those who want to dig into this quite difficult topic here is some guide What Every Computer Scientist Should Know About Floating-Point Arithmetic which is part of even larger guide Numerical Computation Guide.
In .net we have a double data type which is the preferred type for real number operations. In the definition in msdn you will find a information that for instance number 1/10 does not have a exact representation in binary format and operations performed on this value may involve some inaccuracy.

Let’s see how it looks like:

Console.WriteLine("0.1 * 0.1 = {0:R}", 0.1 * 0.1);

we know that the result should be 0.01 while the calculated result is

0.1 * 0.1 = 0,010000000000000002

Things are also bad if we simply add double numbers. Let’s add 1/10 ten times, so we expect to have whole one. What is calculated by floating point arithmetic?

double result = 0.0;
for (int i = 0; i < 10; i++) result += 0.1;
   Console.WriteLine("Result = {0:R}", result);

Result = 0,99999999999999989

What is the solution for such problems? Well there is no ideal solution. One option is to round the result of each operation that involves double numbers. However we need to know what accuracy is enough for our purpose and use a appropriate number of decimal places rounding. Assume we are fine with 3 decimal places accuracy we get then

double result = 0.0;
for (int i = 0; i < 10; i++) result += 0.1;
    Console.WriteLine("{0:R}", Math.Round(result,3));

and we get 1 as a result. Same works with multiplication.
Another option available in .net is the decimal data type. This is a recommended solution for financial and banking applications, provides more accuracy and mitigates the rounding errors. However it does not solve the problem at all, just pushes it further on the accuracy line.