473,735 Members | 6,374 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

sanity check - floating point comparison


template <class T> inline bool isEqual( const T& a, const T& b,
const T epsilon = std::numeric_li mits<T>::epsilo n() )
{
const T diff = a - b;
return ( diff <= epsilon ) && ( diff >= -epsilon );
}

int main()
{
std::deque<doub le> pt ;
pt.push_back ( 2.3123 );
pt.push_back ( 4.3445 );
pt.push_back ( 1.343 );
pt.push_back ( 4.3445 );
pt.push_back ( 4.3445 );
pt.push_back ( 2.3123 );
std::deque<doub le> jt ;
jt.push_back ( 4.3445 );
jt.push_back ( 2.3123 );

std::deque<doub le> results;
// results should have - 1, 3, 4, 0, 5

for ( int idx ( 0 ) ; idx < jt.size(); ++idx )
{
for ( int kdx ( 0 ); kdx < pt.size(); ++kdx )
{
if ( isEqual<double> ( jt [ idx ], pt [ kdx ] ) )
{
results.push_ba ck ( kdx );
}
}
}
std::copy ( results.begin() , results.end(),
std::ostream_it erator<int> ( std::cout, "\n" ) );
}

My intent. I'll search the pt container for the values in the jt
container. If found, I'll store - in the result container - the
index/location where the value was found in the pt container. For
example: Search pt container for first element in jt container. So I
found 4 at postions 1, 3 and 4. Similarily for 2. 2 was found within
the pt container at 0 and 5.

Result will print, 1, 3, 4, 0, 5. Works.

What makes me nervous though is the floating point comparsion. After
all numeric_limits is not defined on one platform (using gcc 2.96).
That said, I was opting to use iterators with - I think std::distance
but I'll end up doing floating point comparison anyways, in which case
my own version ( with my own comparator - isEqual) works best. Correct?

Apr 25 '06 #1
32 4113
In message <11************ **********@u72g 2000cwu.googleg roups.com>,
ma740988 <ma******@gmail .com> writes

template <class T> inline bool isEqual( const T& a, const T& b,
const T epsilon = std::numeric_li mits<T>::epsilo n() )
{
const T diff = a - b;
return ( diff <= epsilon ) && ( diff >= -epsilon );
}

int main()
{
std::deque<doub le> pt ;
pt.push_back ( 2.3123 );
pt.push_back ( 4.3445 );
pt.push_back ( 1.343 );
pt.push_back ( 4.3445 );
pt.push_back ( 4.3445 );
pt.push_back ( 2.3123 );
std::deque<doub le> jt ;
jt.push_back ( 4.3445 );
jt.push_back ( 2.3123 );

std::deque<doub le> results;
// results should have - 1, 3, 4, 0, 5

for ( int idx ( 0 ) ; idx < jt.size(); ++idx )
{
for ( int kdx ( 0 ); kdx < pt.size(); ++kdx )
{
if ( isEqual<double> ( jt [ idx ], pt [ kdx ] ) )
{
results.push_ba ck ( kdx );
}
}
}
std::copy ( results.begin() , results.end(),
std::ostream_it erator<int> ( std::cout, "\n" ) );
}

My intent. I'll search the pt container for the values in the jt
container. If found, I'll store - in the result container - the
index/location where the value was found in the pt container. For
example: Search pt container for first element in jt container. So I
found 4 at postions 1, 3 and 4. Similarily for 2. 2 was found within
the pt container at 0 and 5.

Result will print, 1, 3, 4, 0, 5. Works.

What makes me nervous though is the floating point comparsion. After
all numeric_limits is not defined on one platform (using gcc 2.96).
?
That said, I was opting to use iterators with - I think std::distance
? Use of iterators versus indexing is a completely different question
from how to compare the stored values.
but I'll end up doing floating point comparison anyways, in which case
my own version ( with my own comparator - isEqual) works best. Correct?

IMO no.

I can't imagine anyone deliberately setting out to produce a compiler on
which the same floating literal 2.3123 etc., wouldn't produce the same
double value internally in each place in the code where it's used, if
you use the same compiler flags. (If you're generating the numbers by
arithmetic it's a different matter, of course.)

Even if the compiler did produce different values for the same literal,
there's no reason to suppose that the results would pass isEqual().
epsilon() has its uses in numerical analysis, but I don't think this is
an appropriate one. In effect it's guaranteed that if X==1.0, (a) X and
X + epsilon() are distinct values and (b) X and X + epsilon()/2 are not,
but for other values of X one of those assertions may not be true.

To specify fuzzy floating-point comparisons correctly you generally need
some knowledge of the domain being modelled, but here you're trying to
second-guess a compiler problem that probably doesn't even exist.

Finally, if you really must use your own comparator, don't call it
isEqual.

--
Richard Herring
Apr 25 '06 #2


IMO no.

I can't imagine anyone deliberately setting out to produce a compiler on
which the same floating literal 2.3123 etc., wouldn't produce the same
double value internally in each place in the code where it's used, if
you use the same compiler flags. (If you're generating the numbers by
arithmetic it's a different matter, of course.)

So if I understand you correctly. Simply doing
if ( jt [ idx ] == pt [ kdx ] ) )
would suffice?

Apr 25 '06 #3
Hello,

ma740988 wrote:

template <class T> inline bool isEqual( const T& a, const T& b,
const T epsilon = std::numeric_li mits<T>::epsilo n() )
{
const T diff = a - b;
return ( diff <= epsilon ) && ( diff >= -epsilon );
}

That epsilon is the difference of 1 and the least value strictly greater
than 1. If you take 1000000 and the least value strictly greater than
1000000, than you will see, that the difference is greater than
epsilon. I don't think you want those values to make isEqual return
false.


int main()
{
std::deque<doub le> pt ;
pt.push_back ( 2.3123 );
pt.push_back ( 4.3445 );
pt.push_back ( 1.343 );
pt.push_back ( 4.3445 );
pt.push_back ( 4.3445 );
pt.push_back ( 2.3123 );
std::deque<doub le> jt ;
jt.push_back ( 4.3445 );
jt.push_back ( 2.3123 );
if ( isEqual<double> ( jt [ idx ], pt [ kdx ] ) ) my own version ( with my own comparator - isEqual) works best.
Correct?


Almost, just don't abuse epsilon. Your input values seem to be rounded
to 4 digits after decimal point, so take 1e-4 instead of epsilon. You
will have to add epsilon as parameter to isEqual, either as template
argument via some bypass, or in the function argument, or hardcode
epsilon some other way.

Bernd Strieder
Apr 25 '06 #4

ma740988 wrote:
What makes me nervous though is the floating point comparsion. After
all numeric_limits is not defined on one platform (using gcc 2.96).


You need to upgrade your complier to gcc 3.x at least. Or you try to
find a patch for gcc 2.96 to fix the problem.

Apr 26 '06 #5

Richard Herring wrote:
To specify fuzzy floating-point comparisons correctly you generally need
some knowledge of the domain being modelled, but here you're trying to
second-guess a compiler problem that probably doesn't even exist.

why not ? But it is a fact that gcc 2.96 has a problem in handling
"epsilon" .

Apr 26 '06 #6

ma740988 wrote:

IMO no.

I can't imagine anyone deliberately setting out to produce a compiler on
which the same floating literal 2.3123 etc., wouldn't produce the same
double value internally in each place in the code where it's used, if
you use the same compiler flags. (If you're generating the numbers by
arithmetic it's a different matter, of course.)

So if I understand you correctly. Simply doing
if ( jt [ idx ] == pt [ kdx ] ) )
would suffice?


It doesn't work for float point number.

Apr 26 '06 #7

Bernd Strieder wrote:
That epsilon is the difference of 1 and the least value strictly greater
than 1. If you take 1000000 and the least value strictly greater than
1000000, than you will see, that the difference is greater than
epsilon. I don't think you want those values to make isEqual return
false.
epsilon depends on data type.

Almost, just don't abuse epsilon. Your input values seem to be rounded
to 4 digits after decimal point, so take 1e-4 instead of epsilon. You
will have to add epsilon as parameter to isEqual, either as template
argument via some bypass, or in the function argument, or hardcode
epsilon some other way.


the hard code should work here. But it is not the best way that uses
epsilon.
If the data type is not double but other kind of struct, how do you
deal with it?

struct new_type
{
char x;
int y;
long z;
double w;
}

Apr 26 '06 #8
In message <11************ *********@u72g2 000cwu.googlegr oups.com>,
dan2online <da********@gma il.com> writes

ma740988 wrote:
> >
> IMO no.
>
> I can't imagine anyone deliberately setting out to produce a compiler on
> which the same floating literal 2.3123 etc., wouldn't produce the same
> double value internally in each place in the code where it's used, if
> you use the same compiler flags. (If you're generating the numbers by
> arithmetic it's a different matter, of course.)
>

So if I understand you correctly. Simply doing
if ( jt [ idx ] == pt [ kdx ] ) )
would suffice?


It doesn't work for float point number.


What do you mean "it doesn't work"? Equality is perfectly well defined
for floating types. It just isn't always what you want to test.

--
Richard Herring
Apr 26 '06 #9
In message <11************ *********@u72g2 000cwu.googlegr oups.com>,
dan2online <da********@gma il.com> writes

Bernd Strieder wrote:
That epsilon is the difference of 1 and the least value strictly greater
than 1. If you take 1000000 and the least value strictly greater than
1000000, than you will see, that the difference is greater than
epsilon. I don't think you want those values to make isEqual return
false.
epsilon depends on data type.


Regardless, it's still the wrong thing to use, because it only
approximates "least detectable difference" for values near to 1.0.
Almost, just don't abuse epsilon. Your input values seem to be rounded
to 4 digits after decimal point, so take 1e-4 instead of epsilon. You
will have to add epsilon as parameter to isEqual, either as template
argument via some bypass, or in the function argument, or hardcode
epsilon some other way.


the hard code should work here. But it is not the best way that uses
epsilon.
If the data type is not double but other kind of struct, how do you
deal with it?

struct new_type
{
char x;
int y;
long z;
double w;
}


Then you understand the problem domain it's supposed to be modelling,
and define your comparison accordingly.

--
Richard Herring
Apr 26 '06 #10

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

Similar topics

14
2631
by: Amit Bhatia | last post by:
Hi there. I am cross posting this on comp.lang.c as well: sorry for same. The problem I am facing is as follows: For example: double a= 0.15; double b=2.4; const double VERYTINY =1.e-10; I know b/a = 16 and hence the remainder is zero; but I am not able to find any suitable thing to encode it into in c. for example (fmod(b,a)>VERYTINY) returns true!
4
3313
by: Dave | last post by:
Hi folks, I am trying to develop a routine that will handle sphere-sphere and sphere-triangle collisions and interactions. My aim is to develop a quake style collision engine where a player can interact with a rich 3D environment. Seem to be 90% of the way there! My problems are related to calculations where the result tends to zero (or another defined limit.) Have loads of cases where this kind of interaction occurs but this one
31
3677
by: JS | last post by:
We have the same floating point intensive C++ program that runs on Windows on Intel chip and on Sun Solaris on SPARC chips. The program reads the exactly the same input files on the two platforms. However, they generate slightly different results for floating point numbers. Are they really supposed to generate exactly the same results? I guess so because both platforms are supposed to be IEEE floating point standard (754?) compliant. ...
5
2415
by: Steffen | last post by:
Hi, is it possible to have two fractions, which (mathematically) have the order a/b < c/d (a,b,c,d integers), but when (correctly) converted into floating point representation just have the opposite order? The idea is that the two fractions are almost identical and that the error introduced by going to floating point representation is bigger than the exact difference, but different for the two fractions such that it somehow turns...
7
13991
by: zjut | last post by:
I need to implement the method : round(String name, int index) The given string maybe the every type of float type, ( the msdn given the regax is that : integral-digits]exponential-digits]) and the index is the location after "." in name. First, i should check the given name is a valid float-point, and then, to check the number in name in index locaion is > 0 or not? eg:
14
2614
by: Robert Latest | last post by:
Hi guys, I'm sure this has been beaten to death on this newsgroup, but I can't find it in the CLC FAQ. Consider the following code: -------- double x = some_value_from_somewhere;
33
2769
by: dis_is_eagle | last post by:
hi....i have encountered strange problem regarding floating point comparison...the problem is... main() { float a=0.7; if(0.7 a) printf("hi"); else printf("hello");
18
2835
by: n.torrey.pines | last post by:
I understand that with floats, x*y == y*x, for example, might not hold. But what if it's the exact same operation on both sides? I tested this with GCC 3.4.4 (Cygwin), and it prints 0 (compiled with - g flag) #include <cmath> #include <iostream> int main() {
15
7534
by: arnuld | last post by:
Next month I will start to work on a C++ based Software named CAT++ which is going to provide FORTRAN like arrays in C++ and will be used within Scientific Community and hence will heavily depend on Numerical-Computations. I was reading 29.16 ans 29.17 sections of FAQs: http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.16 as a test, I just tried this program on Linux, GCC 4.2.2 and it gave me 2 different results:
0
8962
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8785
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9463
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
9327
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...
1
9251
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6747
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
4559
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...
1
3273
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
2739
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.