473,796 Members | 2,916 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Comparing floating point numbers

nw
Hi,

I'd like to compare 2 floating point numbers within a given error. I'd
rather not use a absolute error but one related to the number of
values that can be represented between the two floats. I've been
reading: http://www.cygnus-software.com/paper...ringfloats.htm
where the following function is provided to do this:

bool AlmostEqual2sCo mplement(float A, float B, int maxUlps) {
// Make sure maxUlps is non-negative and small enough that the
// default NAN won't compare as equal to anything.
assert(maxUlps 0 && maxUlps < 4 * 1024 * 1024);
int aInt = *(int*)&A;
// Make aInt lexicographical ly ordered as a twos-complement int
if (aInt < 0)
aInt = 0x80000000 - aInt;
// Make bInt lexicographical ly ordered as a twos-complement int
int bInt = *(int*)&B;
if (bInt < 0)
bInt = 0x80000000 - bInt;
int intDiff = abs(aInt - bInt);
if (intDiff <= maxUlps)
return true;
return false;
}

However, as the article states, this relies on a number of compiler
specific features, such as the size of int (and I guess float). It
also relies on the floats using IEEE representation (I guess all
compilers use this, but is it in the standard?).

So my question is this. Is there a good compiler independent method
for comparing floating point numbers with a relative error?

Apr 30 '07 #1
14 2515
nw wrote:
I'd like to compare 2 floating point numbers within a given error. [...]

However, as the article states, this relies on a number of compiler
specific features, such as the size of int (and I guess float). It
also relies on the floats using IEEE representation (I guess all
compilers use this, but is it in the standard?).
Right.
So my question is this. Is there a good compiler independent method
for comparing floating point numbers with a relative error?
double a, b;
...
if ( fabs(a-b) < myepsilon * max(fabs(a),fab s(b)) )
// they are "equal"

Pick myepsilon as you deem fit. That's your "relative error".

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Apr 30 '07 #2
nw
double a, b;
...
if ( fabs(a-b) < myepsilon * max(fabs(a),fab s(b)) )
// they are "equal"

Pick myepsilon as you deem fit. That's your "relative error".
ok, if I'm reading this correctly this will mean that large numbers
are allowed a bigger distance than smaller ones? This isn't exactly
what I want. The function I previously posted allows me to say "are
these two numbers with the X nearest possible floating point values"
is it possible to do that in a compiler independent way?

Apr 30 '07 #3
nw wrote:
> double a, b;
...
if ( fabs(a-b) < myepsilon * max(fabs(a),fab s(b)) )
// they are "equal"

Pick myepsilon as you deem fit. That's your "relative error".

ok, if I'm reading this correctly this will mean that large numbers
are allowed a bigger distance than smaller ones?
Bigger absolute distance, but the same relative distance.
This isn't exactly
what I want.
But that's what "relative" means.
The function I previously posted allows me to say "are
these two numbers with the X nearest possible floating point values"
Huh? Please re-read the statement inside double quotes and try
expressing it in mathematical notation.
is it possible to do that in a compiler independent way?
As soon as I know what exactly (or relatively) it is you want, I'll
try to help.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Apr 30 '07 #4
In message <f1**********@n ews.datemas.de> , Victor Bazarov
<v.********@com Acast.netwrites
>nw wrote:
>> double a, b;
...
if ( fabs(a-b) < myepsilon * max(fabs(a),fab s(b)) )
// they are "equal"

Pick myepsilon as you deem fit. That's your "relative error".

ok, if I'm reading this correctly this will mean that large numbers
are allowed a bigger distance than smaller ones?

Bigger absolute distance, but the same relative distance.
>This isn't exactly
what I want.

But that's what "relative" means.
>The function I previously posted allows me to say "are
these two numbers with the X nearest possible floating point values"

Huh? Please re-read the statement inside double quotes and try
expressing it in mathematical notation.
>is it possible to do that in a compiler independent way?

As soon as I know what exactly (or relatively) it is you want, I'll
try to help.
I think you need to read the cited article to find out what this is
about. This isn't really a "relative error", it's asking the question
"is the number of representable floating-point values between given A
and B less than N?"

--
Richard Herring
Apr 30 '07 #5
nw
I think you need to read the cited article to find out what this is
about. This isn't really a "relative error", it's asking the question
"is the number of representable floating-point values between given A
and B less than N?"
Yes what he said. :)

Sorry, the question wasn't defined as clearly as it could have been.
So is there any compiler independent method for this? Or is it perhaps
not even a particularly good idea?

Apr 30 '07 #6
Richard Herring wrote:
[...]
I think you need to read the cited article to find out what this is
about. This isn't really a "relative error", it's asking the question
"is the number of representable floating-point values between given A
and B less than N?"
Right. My fault for not reading the article, and I think we can call
it "relative error" after all. Each of the "next representable FP
number" from a certain value differs from it on a relative basis (the
exponent plays the part of the scaling factor).

To the OP:

It can be done, but only if the platform does have the integral type
large enough to represent the floating point representation, and that
the FP representation and the integral representation share the same
base (2). The information is available through 'std::numeric_l imits'
specialisations , take a look.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Apr 30 '07 #7
nw wrote:
>I think you need to read the cited article to find out what this is
about. This isn't really a "relative error", it's asking the question
"is the number of representable floating-point values between given A
and B less than N?"

Yes what he said. :)

Sorry, the question wasn't defined as clearly as it could have been.
So is there any compiler independent method for this? Or is it perhaps
not even a particularly good idea?
Since there is no requirement that FP values are represented in the same
base as integral values, the answer is most likely "no".

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Apr 30 '07 #8
"nw" <ne*@soton.ac.u kwrote in message
news:11******** **************@ h2g2000hsg.goog legroups.com...
>I think you need to read the cited article to find out what this is
about. This isn't really a "relative error", it's asking the question
"is the number of representable floating-point values between given A
and B less than N?"

Yes what he said. :)

Sorry, the question wasn't defined as clearly as it could have been.
So is there any compiler independent method for this? Or is it perhaps
not even a particularly good idea?
You need the C99 function nexttoward, which does almost exactly what
you want. It'll be a part of the next C++ Standard, but right now it's
relatively rare. See our Compleat Library, available at our web site.

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
Apr 30 '07 #9
nw
You need the C99 function nexttoward, which does almost exactly what
you want. It'll be a part of the next C++ Standard, but right now it's
relatively rare. See our Compleat Library, available at our web site.
Yep that does sound like what I want. I guess I'll just have to test
within absolute limits for now and patiently await the new C standard.

Thanks for your help!

Apr 30 '07 #10

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

Similar topics

4
3317
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
687
23768
by: cody | last post by:
no this is no trollposting and please don't get it wrong but iam very curious why people still use C instead of other languages especially C++. i heard people say C++ is slower than C but i can't believe that. in pieces of the application where speed really matters you can still use "normal" functions or even static methods which is basically the same. in C there arent the simplest things present like constants, each struct and enum...
11
2395
by: John | last post by:
Hi, I encountered a strange problem while debugging C code for a Windows-based application in LabWindows CVI V5.5, which led me to write the test code below. I tried this code with a different compiler and got the same erroneous result on two different PCs (with OS Win98 & Win98SE), so it appears to be a problem with ANSI C. I thought that negative double variables could be compared as easily and *reliably* as integers, but apparently...
15
3935
by: michael.mcgarry | last post by:
Hi, I have a question about floating point precision in C. What is the minimum distinguishable difference between 2 floating point numbers? Does this differ for various computers? Is this the EPSILON? I know in float.h a FLT_EPSILON is defined to be 10^-5. Does this mean that the computer cannot distinguish between 2 numbers that differ by less than this epsilon?
32
4122
by: ma740988 | last post by:
template <class T> inline bool isEqual( const T& a, const T& b, const T epsilon = std::numeric_limits<T>::epsilon() ) { const T diff = a - b; return ( diff <= epsilon ) && ( diff >= -epsilon ); } int main() { std::deque<double> pt ;
12
6861
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?
27
3871
by: Thomas Kowalski | last post by:
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
18
2895
by: eman.abu.samra | last post by:
Hi all, i have encountered the strangest behavior. Check out this simple program: #include <stdio.h> int main() { double time = 1;
5
4519
by: saneman | last post by:
I have a function: int F(double a) { if (a = =1.0) { return 22; } return 44; }
0
9685
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
9536
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,...
1
10205
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,...
0
10021
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9063
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
6802
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
5582
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4131
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
3
2933
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.