floating-numbers , almostEqual function

I'm using Arduino cookbook second edition , I saw an example using floating-numbers

I couldn't understand it not all of it but the Function that he have made , please if anyone can

can gives this informations in detail I will be so greatfull

/
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;
}

I couldn't understand it not all of it but the Function that he have made , please if anyone can

can gives this informations in detail I will be so greatfull

What don't you understand? If a and b are floats, then they are almost equal if the difference is small. So, if a is 0 and b is very small, then they are almost equal. If b is 0 and a is very small, then they are almost equal. If neither value is 0, but the difference between them is very small, then they are almost equal.

no, I understand that part

I'm talking about the main code, how does it work

I'm talking about the main code, how does it work

The variable called value starts with an initial value. On every pass through loop(), the value is made smaller. The new value is then tested to see if it is exactly 0, almost equal to 0, or not even close to 0.

PaulS:
The variable called value starts with an initial value. On every pass through loop(), the value is made smaller. The new value is then tested to see if it is exactly 0, almost equal to 0, or not even close to 0.

ok, I see

now if you don't mind I want the full Explanation, block by block

donzoma:
no, I understand that part

I'm talking about the main code, how does it work

I highly recommend that you study C++. After some simple research and learning exercises, you would be able to analyze this very easily yourself.

Note that these two lines are an absolute comparison with delta

if (a == 0) return fabs(b) <= DELTA;
if (b == 0) return fabs(a) <= DELTA;

while this line is a relative comparison with delta

return fabs((a - b) / max(fabs(a), fabs(b))) <= DELTA;

donzoma
I think the part that maybe troubling you is value = value - 0.1 Think of it as

Value

  • 0.1
    = Value

In this example the top Value is equal to .9 after the math the bottom part is equal to .8. every time Value is call in the program from here on. it will equal .8

When the program goes back to the top, the top Value will equal .8.