473,713 Members | 6,107 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 4106
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
2629
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
3310
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
3673
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
2413
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
13990
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
2613
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
2764
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
2831
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
7533
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
8795
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
9167
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
7941
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...
0
5942
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4459
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
4714
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3154
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
2509
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2101
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.