 # Using floats.

I’m using the Arduino cookbook in which to understand the C+ programming.
This is one of the examples given on using the floating-point numbers. Understandably I get that
the number cannot equal exactly zero; however, I don’t know what is meant exactly with the almostequal function
utilizing the return and fabs coding at the bottom. I just need a simple explanation.

``````/*
floating-point example
*/

float value = 1.1;

void setup() {
Serial.begin(9600);
}

void loop() {
value = value - 0.1;
if (value == 0) {
Serial.println("the value is exactly zero");
}
else if (almostEqual(value, 0)) {
Serial.print("the value");
Serial.print(value,7); // print to 7 decimal places
Serial.println(" is almost to equal");
}
else {
Serial.println (value);
}
delay(100);
}
//returns true if the difference between a and b is small
// set value of DELTA to the maximum difference considered to be equal

boolean almostEqual(float a, float b) {
const float DELTA = .00001; // max difference to be almost equal
if (a == 0) return fabs(b) <= DELTA;
if (b == 0) return fabs(a) <= DELTA;
return fabs((a - b) / max(fabs(a), fabs(b))) <= DELTA;

}
``````

however, I don't know what is meant exactly with the almostequal function

fabs() is the floating point, absolute value function. It returns a positive value, regardless of whether the input was positive or negative.

That code is determining, if one of the values is exactly 0, whether the other one is small enough to be almost equal to 0. If neither value is 0, it determines if the absolute value of the difference between the values is small enough to be almost equal to 0.

Why is DELTA being used. Is delta the allowed difference between a & b? How would you describe the if functions of a & b? Also, given that when I run the code the value being printed is -0.0000001 which is the most allowed to be printed. 7 digits.

infinite4566: Why is DELTA being used. Is delta the allowed difference between a & b?

When one of the numbers is exactly 0, then DELTA is the absolute difference that is considered "equal". If the values are both non-zero, then a relative difference is computed. And if the values are within 0.001% (DELTA as a %) they are considered equal.

DELTA is basically setting the tolerance for equivalence, and looks to have been chosen to about match the actual useful resolution of 32-bit floats, which would be a good choice.