Discussion:
About comparing two double
(too old to reply)
Tony Johansson
2016-05-10 15:18:06 UTC
Permalink
Hello!

Can somebody tell we if this simple method hold for comparing two double for
nearly equality.
I have tried several example with this method and it seems to compare
correct.
I mean as long as the abs value between them is smallen then my epilon set
to 0.001 it seems to work fine.

I just want to know if somebody can tell me when this method should return
true but return false when comparing two double.

public static bool NearlyEqual(double a, double b, double epsilon)
{
if (Math.Abs(a-b) < epsilon)
{
return true;
}

return false;
}

//Tony
Stefan Ram
2016-05-10 15:47:02 UTC
Permalink
Post by Tony Johansson
Can somebody tell we if this simple method hold for comparing two double for
nearly equality.
First, one should define when two double values are deemed
to be »nearly equal« /in English/. (There is no such definition
that is generally accepted yet.)

Then, we can tell, whether a given algorithm implements this
definition correctly.
Arne Vajhøj
2016-05-11 01:53:36 UTC
Permalink
Post by Tony Johansson
Can somebody tell we if this simple method hold for comparing two double
for nearly equality.
I have tried several example with this method and it seems to compare
correct.
I mean as long as the abs value between them is smallen then my epilon
set to 0.001 it seems to work fine.
I just want to know if somebody can tell me when this method should
return true but return false when comparing two double.
public static bool NearlyEqual(double a, double b, double epsilon)
{
if (Math.Abs(a-b) < epsilon)
{
return true;
}
return false;
}
The code tests for whether the difference between two doubles are less
than a given threshold.

Whether that implies "nearly equality" in your context is something
only you can tell.

Two comments though:

1) 0.001 is a pretty big number in many contexts - if used for testing
for stability of an iterative algorithm, then in many cases it will
not produce the best result

2) It is absolute based not relative based. 0.0000001 and 0.0001 will
be considered equal even though there is a factor 1000 in
difference. That may be fine or may be a problem depending on the
context.

To handle the second issues I have sometime used the following
code (C++):

// small number
const double FP_SMALL = 0.000001;
const double FP_ABS_SMALL_1 = -FP_SMALL;
const double FP_ABS_SMALL_2 = FP_SMALL;
const double FP_REL_SMALL_1 = 1-FP_SMALL;
const double FP_REL_SMALL_2 = 1+FP_SMALL;

// comparisons
BOOL num_eq(double x1,double x2)
{
double d;
if((-1<x2)&&(x2<1)) {
d = x1 - x2;
return ((FP_ABS_SMALL_1<d)&&(d<FP_ABS_SMALL_2));
} else {
d = x1 / x2;
return ((FP_REL_SMALL_1<d)&&(d<FP_REL_SMALL_2));
}
}

But that is not more or less correct than many other approaches.

Arne

Loading...