Writing a macro for checking close enough floating points.

P

pereges

Hi, I'm trying to write a macro for the relative difference function
which is used to check the close enough floating point values. Is
this correct way to write it ? :

#define EPSILON 0.000001
#define max(x, y) ((x) > (y) ? (x) : (y))
#define eq(a, b) max(fabs(a), fabs(b)) == 0.0 ? 0.0 : fabs(a - b) /
(max(fabs(a), fabs(b)))

Now for checking if two doubles, say x and y, are close we use eq(a,b)
<= EPSILON
 
N

Nick Keighley

Hi, I'm trying to write a macro for the relative difference function
which is used to check the close enough floating point values.  Is
this correct way to write it ? :

#define EPSILON 0.000001
#define max(x, y) ((x) > (y) ?  (x) : (y))
#define eq(a, b)  max(fabs(a), fabs(b)) == 0.0 ? 0.0 : fabs(a - b) /
(max(fabs(a), fabs(b)))

Now for checking if two doubles, say x and y, are close we use eq(a,b)
<= EPSILON

can you get almost-divide-by-ero if a and b are very small?
For instance what if
a == b == 1e-53 (or some other very non-zero number)
 
N

Nick Keighley

the error rate in my posts seems to be climbing...


Hi, I'm trying to write a macro for the relative difference function
which is used to check the close enough floating point values.  Is
this correct way to write it ? :
#define EPSILON 0.000001
#define max(x, y) ((x) > (y) ?  (x) : (y))
#define eq(a, b)  max(fabs(a), fabs(b)) == 0.0 ? 0.0 : fabs(a - b) /
(max(fabs(a), fabs(b)))
Now for checking if two doubles, say x and y, are close we use eq(a,b)
<= EPSILON

can you get almost-divide-by-[z]ero if a and b are very small?
For instance what if
 a == b == 1e-53 (or some other very [small] non-zero number)

--Nick Keighley
 
G

~Glynne

Hi, I'm trying to write a macro for the relative difference function
which is used to check the close enough floating point values.  Is
this correct way to write it ? :

#define EPSILON 0.000001
#define max(x, y) ((x) > (y) ?  (x) : (y))
#define eq(a, b)  max(fabs(a), fabs(b)) == 0.0 ? 0.0 : fabs(a - b) /
(max(fabs(a), fabs(b)))

Now for checking if two doubles, say x and y, are close we use eq(a,b)
<= EPSILON

Just use Knuth's fcmp(). It accounts for a number of subtle issues,
which are (nearly) impossible to capture in a simple macro.

Download it from
http://fcmp.sourceforge.net/

~Glynne
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top