Dear All,

I want to do two mathematical operations, say

``a / b``

and

``c / d``

then test whether they are equal. I'm really very bad at computer errors, I think I need to read more about it (any reference is welcome). So, my question is: What is a suitable EPSILON to tolerate some computational errors in general? I know this depends on the complexity of the operation itself (because of propagating the errors at different steps of computation)... but what is a suitable start?

``````bool equals(double n1, double n2)
{
return ((n1 - n2 <= EPSILON) || (n2 - n1 <= EPSILON));
}``````

## All 4 Replies

First you might not have declered EPSILON
secondly why are you subtracting n1 and n2? Isn't n1 and n2 the resluts of a/b and c/d?
if you want to test if they where equal

``````if (n1 == n2)
{
EPSILON = true;
}``````

and you cant return this (... == ... || ... >-...)

``````bool equals(double n1, double n2)
{
bool EPSILON = false;
if (n1 == n2)
{
EPSILON = true;
}
return EPSILON;

}``````

This is a question about tolerance of accuracy and it does depend on the application that you are using as a rough

rule of thumb I use the 0.000001; if I am looking for a stop condition
but you can go smaller if you
have the ratios
Consider:
(a*d == c*b) easier to establish the range of error

but the answer depends on the problem you are dealing with.

it is unusual to be comparing ratios normally you are comparing to 0
if you are looking
The matissa and the exponent
there are 32 bits for each available and it is the scale of the numbers that can be questionable if the numbers are the same order of magnitude then a single calculation the error will be very small.
10^356 - 0.999999999999*10^356
still gives an error of 10^344
so a tolerance will be normally
(a - b )/ b
so the error mainly comes from the mantissa not being enough digits
which if checking for 0 is probably 31 bits accurate for a single calculation so the ratio fo errors is about 1 / 2 000 000 000

Without a precise application this cannot be quantified I have had a problem using floats often but doubles extremely rarely.

Most errors come from the interpretation of non-base 2 numbers in the wrong format so that

float f(10000.0);
should be
float f(10000.0f);

If you want to see if a/b == c/d , then all you have to check if
a == c && b == d; More specifically, if a == kc && b == kd where k is
an element from the natural numbers.

In layman's terms:

What precision do you need? If 3 decimals, an EPSILON of .000x or smaller would work.

invisi, it is not recommended to compare doubles for equality. The value 25 could be 25.0000001 or 24.9999999. Both are essentially equal, but floating point values are rarely exact.

commented: the "compare a float bug", it's classic :) +12
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.