# Question about grammar for the boolean function

Below is a section of one of the first sketches from Arduino Cookbook. It works properly, but I’m confused about how it is written. Does ‘if(a==0) return fabs(b) <= DELTA’ mean that, if float a is exactly equal to 0 then make DELTA equal to the absolute value of b? In the phrase ‘return fabs((a-b) / max(fabs(a), fabs(b))) <= DELTA;’, what does the term ‘max(fabs(a), fabs(b)))’ mean? I believe I can puzzle out how this works if I have those two pieces of information. Thanks.

boolean almostEqual(float a, float b)
{
const float DELTA = .00001;
if(a==0) return fabs(b) <= DELTA;
if(b==0) return fabs(a) <= DELTA;
return fabs((a-b) / max(fabs(a), fabs(b))) <= DELTA;
}

One way to figure this out is to supply sample values for a and b (e.g., a = .003, b = .0029) and keep in mind that the type specifier for the function is boolean. Once you see what those values return, make them smaller until they approach DELTA. You should be able to see what the function does.

Let’s rewrite it

``````// -------------------------------------------
// Function : almostEqual
// Test if two floats are almost equal within a relative delta.
// If they are equal, return true, else return false.
boolean almostEqual(float a, float b)
{
// Declare the maximum relative difference between a and b.
const float DELTA = .00001;

// Extra test for when one of the parameter is zero.
if (a == 0.0)
{
if ( fabs(b) <= DELTA )
return true;
else
return false;
}
if (b==0.0)
{
if (fabs(a) <= DELTA)
return true;
else
return false;
}

// calculate the difference
// find maximum absolute value
float max = max ( fabs(a), fabs(b) );

// calculate the difference relative to the floats.
float diff = fabs( (a-b) / max );

if (diff <= DELTA)
return true;
else
return false;
}
``````

Hello and welcome fabs( f ) return the absolute value of float f: it will always return the positive value of the float. For example with f = 0.1 it will return 0.1, and with f = -0.1 it will also return 0.1.

Using this function remove the need to manually do 2 comparisons.

So instead of writing:

``````if ( ( f < 0 && f >= -DELTA ) || ( f > 0 && f <= DELTA ) )
``````

You can just write:

``````if ( fabs( f ) <= DELTA )
``````

And max( a, b ) will return either a or b, depending which one is greater.