473,698 Members | 2,833 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Comparing doubles

Hi everyone,
To determine equality of two doubles a and b the following is often
done:

bool isEqual ( double a, double b ) {
return ( fabs (a-b) < THRESHOLD );
}

But this a approach usually fails if comparing doubles of different
magnitude since it's hard or not possible to find a suitable threshold
value. Since an double consists of mantissa, exponent and sign I
assume that the "best" way in this case would be to just "ignore" the
last few (e.g. 4-8 bits) of the mantissa to check for equality (at
least for the x86 architecture, which follow IEEE 754). Have someone
here ever tried to implement a similar approach? If yes, which
experiences have been made?

However my first approach to implement this failed. Can anyone tell
what I might have done wrong?

union IEEErepresentat ion {
long long man : 52;
int exp : 11;
int sign : 1;
};

union IEEEdouble {
double d;
IEEErepresentat ion c;
};

const int number_of_bits_ to_ignore = 8;

bool isEqual (double a, double b) {
IEEEdouble aa, bb;
aa.d = a;
bb.d = b;
return ((aa.c.man << number_of_bits_ to_ignore) == (bb.c.man <<
number_of_bits_ to_ignore));
}

int main() {
string a = isEqual (1324.567890123 4, 1324.5678901256 ) ? "true" :
"false";
string b = isEqual (134.5678901234 , 134.5678901256 ) ? "true" :
"false";
string c = isEqual (.5678901234, .5678901256 ) ? "true" : "false";
string d = isEqual (1324.567890123 4, 124.5678901256 ) ? "true" :
"false";
string e = isEqual (134.5678901234 , 134.5178901256 ) ? "true" :
"false";
string f = isEqual (.5678901234, .3678901256 ) ? "true" : "false";

cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl;
cout << "d = " << d << endl;
cout << "e = " << e << endl;
cout << "f = " << f << endl;
return 0;
}

Thanks in advance,
Thomas Kowalski

Jul 9 '07 #1
27 3853
Thomas Kowalski a écrit :
Hi everyone,
To determine equality of two doubles a and b the following is often
done:

bool isEqual ( double a, double b ) {
return ( fabs (a-b) < THRESHOLD );
}

But this a approach usually fails if comparing doubles of different
magnitude since it's hard or not possible to find a suitable threshold
value.
std::numeric_li mits<double>::e psilon() is a good starting point.
Since an double consists of mantissa, exponent and sign I
assume that the "best" way in this case would be to just "ignore" the
last few (e.g. 4-8 bits) of the mantissa to check for equality (at
least for the x86 architecture, which follow IEEE 754). Have someone
here ever tried to implement a similar approach? If yes, which
experiences have been made?
I did try to make an switchsign() fuction by reseting the SIGN bit. It
was less efficient than a=-a;

And you realize of course that you may succeed on your compiler and
architecture but it will likely fail on others'.
>
However my first approach to implement this failed. Can anyone tell
what I might have done wrong?

union IEEErepresentat ion {
long long man : 52;
int exp : 11;
int sign : 1;
};
Here, you must mean struct.
>
union IEEEdouble {
double d;
IEEErepresentat ion c;
};

const int number_of_bits_ to_ignore = 8;

bool isEqual (double a, double b) {
IEEEdouble aa, bb;
aa.d = a;
bb.d = b;
return ((aa.c.man << number_of_bits_ to_ignore) == (bb.c.man <<
number_of_bits_ to_ignore));
}
Should be >>. Little endian inverts bytes, not bits

Michael
Jul 9 '07 #2
On Jul 9, 12:07 pm, Thomas Kowalski <t...@gmx.dewro te:
[...]

union IEEErepresentat ion {
long long man : 52;
int exp : 11;
int sign : 1;

};
Why is this a union?
[...]
Jul 9 '07 #3
"Thomas Kowalski" wrote:
Hi everyone,
To determine equality of two doubles a and b the following is often
done:

bool isEqual ( double a, double b ) {
return ( fabs (a-b) < THRESHOLD );
}

But this a approach usually fails if comparing doubles of different
magnitude since it's hard or not possible to find a suitable threshold
value. Since an double consists of mantissa, exponent and sign I
assume that the "best" way in this case would be to just "ignore" the
last few (e.g. 4-8 bits) of the mantissa to check for equality (at
least for the x86 architecture, which follow IEEE 754). Have someone
here ever tried to implement a similar approach? If yes, which
experiences have been made?
<snip>

I think bit fiddling should be a last resort, it forces anyone encountering
the code to go through the same torturous process you went through when you
coded it.

Have you looked to see what you can do with the notion of "relative error"?
Jul 9 '07 #4
Why is this a union?>
Right, this should of course be a struct.

Regards,
Tk

Jul 9 '07 #5
On Jul 9, 2:43 pm, "osmium" <r124c4u...@com cast.netwrote:
Have you looked to see what you can do with the notion of "relative error"?
Something like the following don't work really well, either for small
numbers (e.g. 0.0000031234434 ).

bool isEqual ( double a, double b ) {
return ( fabs ((a-b)/b < std::numeric_li mits<double>::e psilon() );
}

Jul 9 '07 #6
But this a approach usually fails if comparing doubles of different
magnitude since it's hard or not possible to find a suitable threshold
value.

std::numeric_li mits<double>::e psilon() is a good starting point.
Does it work for this test set? Maybe I did something wrong, but for
me its not working well.
ASSERT ( isEqual (12345678901234 56, 123456789012345 7 ) );
ASSERT ( isEqual (1.234567890123 456, 1.2345678901234 57 ) );
ASSERT ( isEqual (0.000001234567 890123456,
0.0000012345678 90123457 ) );

I did try to make an switchsign() fuction by reseting the SIGN bit. It
was less efficient than a=-a;

And you realize of course that you may succeed on your compiler and
architecture but it will likely fail on others'.
I do. It's a pity that there is no better way to do this (or at least
I don't know it).

Here, you must mean struct.
Yes, true.
Should be >>. Little endian inverts bytes, not bits
With ">>" its not really working either. I assume there is a problem
with shifting a 52 bit number?

Regards,
Thomas
Jul 9 '07 #7
Thomas Kowalski a écrit :
On Jul 9, 2:43 pm, "osmium" <r124c4u...@com cast.netwrote:
>Have you looked to see what you can do with the notion of "relative error"?

Something like the following don't work really well, either for small
numbers (e.g. 0.0000031234434 ).

bool isEqual ( double a, double b ) {
return ( fabs ((a-b)/b < std::numeric_li mits<double>::e psilon() );
}
If a = b + 10 and a!=b and b very big, the above assumption will be
true but a!=b.

The equality can be:
abs(x - y) < std::numeric_li mits<double>::e psilon()

And inequality less or equal can be of the same format without abs:
x - y < std::numeric_li mits<double>::e psilon();

Michael
Jul 9 '07 #8
Thomas Kowalski a écrit :
>>But this a approach usually fails if comparing doubles of different
magnitude since it's hard or not possible to find a suitable threshold
value.
std::numeric_l imits<double>:: epsilon() is a good starting point.

Does it work for this test set? Maybe I did something wrong, but for
me its not working well.
ASSERT ( isEqual (12345678901234 56, 123456789012345 7 ) );
ASSERT ( isEqual (1.234567890123 456, 1.2345678901234 57 ) );
ASSERT ( isEqual (0.000001234567 890123456,
0.0000012345678 90123457 ) );
On my system, epsilon is 2.22045e-16. It is normal the first two assert
trigger a fault, the third not.
>
>I did try to make an switchsign() fuction by reseting the SIGN bit. It
was less efficient than a=-a;

And you realize of course that you may succeed on your compiler and
architecture but it will likely fail on others'.

I do. It's a pity that there is no better way to do this (or at least
I don't know it).

>Here, you must mean struct.
Yes, true.
>Should be >>. Little endian inverts bytes, not bits

With ">>" its not really working either. I assume there is a problem
with shifting a 52 bit number?
No reason for that. Perhaps you can try simply to mask the double:
union dl
{
double d;
unsigned long l;
};

dl d1=0.0000012345 67890123456;
dl d2=0.0000012345 67890123457;

unsigned long mask = (~0)<<nb_bit;

if ( (d1.l&mask) == (d2.l&mask) )
{
// Equal !!!
}

I didn't try but it is not far from the solution you seek.

Michael
Jul 9 '07 #9
Michael DOUBEZ wrote:
Thomas Kowalski a écrit :
>>>But this a approach usually fails if comparing doubles of different
magnitude since it's hard or not possible to find a suitable
threshold value.
std::numeric_ limits<double>: :epsilon() is a good starting point.

Does it work for this test set? Maybe I did something wrong, but for
me its not working well.
ASSERT ( isEqual (12345678901234 56, 123456789012345 7 ) );
ASSERT ( isEqual (1.234567890123 456, 1.2345678901234 57 ) );
ASSERT ( isEqual (0.000001234567 890123456,
0.000001234567 890123457 ) );

On my system, epsilon is 2.22045e-16. It is normal the first two
assert trigger a fault, the third not.
>>
>>I did try to make an switchsign() fuction by reseting the SIGN bit.
It was less efficient than a=-a;

And you realize of course that you may succeed on your compiler and
architectur e but it will likely fail on others'.

I do. It's a pity that there is no better way to do this (or at least
I don't know it).

>>Here, you must mean struct.
Yes, true.
>>Should be >>. Little endian inverts bytes, not bits

With ">>" its not really working either. I assume there is a problem
with shifting a 52 bit number?

No reason for that. Perhaps you can try simply to mask the double:
union dl
{
double d;
unsigned long l;
};

dl d1=0.0000012345 67890123456;
dl d2=0.0000012345 67890123457;

unsigned long mask = (~0)<<nb_bit;

if ( (d1.l&mask) == (d2.l&mask) )
{
// Equal !!!
}

I didn't try but it is not far from the solution you seek.
The problem with using 'union' like that is that it's undefined.

If portability is a requirement, it's better to extract the mantissa
from each value and compare those; see 'frexp' function in <cmath>.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jul 9 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
7867
by: nicolas | last post by:
I was very surprised by the output of the following program: #include <iostream> #include <numeric> int main() { double vals_1= { 0.5, 0.2, 0.1, 0.1, 0.1 }; double vals_2= { 0.1, 0.1, 0.1, 0.2, 0.5 }; double sum1 = std::accumulate( vals_1, vals_1+5, 0. );
4
2842
by: Matt Billock | last post by:
Hello everyone, I am having some issues with what should be an insanely simple problem. Basically, I'm working on an implementation of the TSP algorithm (I have a static set of 5 locations, so I'm just brute forcing my way through it), and during execution I build a list of 120 potential distances to be travelled, stored in an array of type double. I then have another function which traverses this array and locates the position of the...
1
2053
by: David Veeneman | last post by:
What's the best way to compare doubles? I am testing a method that should return the fraction 2/9. For my expected result, I entered 0.222222 (a six decimal place representation of 2/9). The CLR resolved the fraction to full precision, so I got this error back from my test: expected:<0.222222> but was:<0.222222222222222> For my purposes, the two values are equal.
6
11574
by: utab | last post by:
Hi there, I would like to compare the values in two vectors of double. I can do it by using iterators, I had an idea but wondering there is a library facility to do that. vector<double> a; vector<double> b; and that is enough for me to check the first three or four values of
12
6849
by: John Smith | last post by:
This code for the comparison of fp types is taken from the C FAQ. Any problems using it in a macro? /* compare 2 doubles for equality */ #define DBL_ISEQUAL(a,b) (fabs((a)-(b))<=(DBL_EPSILON)*fabs((a))) Do the same issues involved in comparing 2 fp types for equality apply to comparing a float to zero? E.g. is if(x == 0.0) considered harmful?
0
9170
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9031
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7741
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6531
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4372
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4624
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3052
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2341
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2007
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.