468,510 Members | 1,768 Online

Writing a macro for checking close enough floating points.

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
Jun 29 '08 #1
3 2203
On 29 Jun, 12:29, pereges <Brol...@gmail.comwrote:
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)
--
Nick Keighley
Jul 22 '08 #2
the error rate in my posts seems to be climbing...
On 22 Jul, 15:52, Nick Keighley <nick_keighley_nos...@hotmail.com>
wrote:
On 29 Jun, 12:29, pereges <Brol...@gmail.comwrote:
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
--
Nick Keighley

Jul 23 '08 #3
On Jun 29, 5:29*am, pereges <Brol...@gmail.comwrote:
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.