# Writing a macro for checking close enough floating points.

Discussion in 'C Programming' started by pereges, Jun 29, 2008.

1. ### peregesGuest

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

pereges, Jun 29, 2008

2. ### Nick KeighleyGuest

On 29 Jun, 12:29, pereges <> wrote:

> 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

Nick Keighley, Jul 22, 2008

3. ### Nick KeighleyGuest

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

On 22 Jul, 15:52, Nick Keighley <>
wrote:
> On 29 Jun, 12:29, pereges <> wrote:
>
> > 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

Nick Keighley, Jul 23, 2008
4. ### ~GlynneGuest

On Jun 29, 5:29 am, pereges <> wrote:
> 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.