0

A program I was writing had a weird output, which I boiled down to the behavior of the following code:

class Program
{
    public static void Main()
    {
        double test1 = 0.1;
        double test2 = Math.Pow(10, -4);
        double test3 = 0.1+Math.Pow(10, -4);
    }
 }

When I check the values of test1, test2, and test3 in debug mode, the values of the first two variables are

test1 = 0.1

test2 = 0.0001

which is what I assigned them to be, but their sum becomes

test3 = 0.10010000000000001.

There appears to be an error of 10^{-17}. My questions are:

  • Why does this happen?
  • Can I do anything to prevent it?

Thanks.

HowDoICSharply
  • 547
  • 1
  • 7
  • 20
  • 7
    Use `decimal` instead of `double` and see [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Habib Jan 29 '16 at 21:13
  • 1
    Thanks @Habib, I couldn't find that similar question when searching the site. I will have a look. – HowDoICSharply Jan 29 '16 at 21:17

0 Answers0