I have a simple example application here where I am multiplying and adding double
variables and then comparing them against an expected result. In both cases the result is equal to the expected result yet when I do the comparison it fails.
static void Main(string[] args)
{
double a = 98.1;
double b = 107.7;
double c = 92.5;
double d = 96.5;
double expectedResult = 88.5;
double result1 = (1*2*a) + (-1*1*b);
double result2 = (1*2*c) + (-1*1*d);
Console.WriteLine(String.Format("2x{0} - {1} = {2}\nEqual to 88.5? {3}\n", a, b, result1, expectedResult == result1));
Console.WriteLine(String.Format("2x{0} - {1} = {2}\nEqual to 88.5? {3}\n", c, d, result2, expectedResult == result2));
Console.Read();
}
And here is the output:
2x98.1 - 107.7 = 88.5
Equal to 88.5? False
2x92.5 - 96.5 = 88.5
Equal to 88.5? True
I need to be able to capture that it is in fact True
in BOTH cases. How would I do it?
There is a whole school of thought that is against using
Double.Epsilon
and similar numbers...I think they use this: (taken from https://stackoverflow.com/a/2411661/613130 but modified with the checks for
IsNaN
andIsInfinity
suggested here by nobugzThe
1E-15
"magic number" is based on the fact thatdouble
s have a little more than 15 digits of precision.I'll add that for your numbers it returns true :-)
Simply change your rounding to level 2 , this will give TRUE
using the debugger,
So when using the double ,these are not equal.
using Math.Round() will round result1 to the correct decimal
Floating point numbers often don't contain the exact value that mathematics tells us, because of how they store numbers.
To still have a reliable comparison, you need to allow some difference:
Please also make sure to read this blog post.
It's a problem with how floating point numbers are represented in memory.
You should read this to get a better understanding of whats going on: What Every Computer Scientist Should Know About Floating-Point Arithmetic