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.