Hello,
Is there an easy way in C# to compare the value of two floats(or doubles), to check that they are equal to each other, within a tolerance of, say, 5, significant figures.
Is there anything available that will do this for me?
Jason
Printable View
Hello,
Is there an easy way in C# to compare the value of two floats(or doubles), to check that they are equal to each other, within a tolerance of, say, 5, significant figures.
Is there anything available that will do this for me?
Jason
Yes, you want to use a sigma and check that against the abs of the difference between the two. Also, this is how you should *always* compare FP numbers.
Code:float sigma = 0.000001f;
float a = 1.237439;
float b = 1.237438;
if( Math.Abs( a - b ) < sigma )
{
// equal
}
That only works for small floating point numbers. If you expect to use large numbers, you may be better off using a ratio of some kind. Deciding when two floating point numbers are more or less equal is actually quite difficult ;)
It works for any precision you like, you just have to define the sigma.
Which is exactly where the problem lies :) There is no fixed sigma that will work for all ranges of numbers. For example, I'd consider 1.000 and 1.001 to be the same. I'd also consider 1x10^10 and 1.001x10^10 to be the same, even though the difference is tens of billions. How would you cope with that?Quote:
you just have to define the sigma.
I understand your point, but in practice we typically only need some fixed precision (as in this case of 5 decimal places) and only deal with the product of some calculation (i.e., the results of 1x10^10 and 1.001x10^10). I'm not sure why you would consider those two expressions to be close to the same though as they will obviously differ by a large amount after being raised to the tenth power.
It all depends on your metric and your usecase. That's why I said it's not a simple thing to do. It's most definitely not so simple that comparing the difference of the two numbers to a tiny number like 0.00001 should be considered as 'how you should always compare FP numbers'. There are places where this would be completely useless. If your numbers are in the 10,000's or 100,000's it's possible that computing the same value two different ways will yield a difference greater than 0.00001 even thoug mathematically the two calculations are identical.Quote:
I'm not sure why you would consider those two expressions to be close to the same though as they will obviously differ by a large amount