[SOLVED] Precision when comparing floats

Hi,
I am trying to compare two floats, but I don't think it is being precise at all.

My sketch:

float oldValue;
void loop() {
  // value is set up here by some sensors. It is a float
  
  if (value != oldValue) {
  	  Serial.println(value);
	  Serial.println(oldValue);
  	  Serial.println("----");
    }
  oldValue = value;
}

The output:

35.60
0.00
----
35.59
35.60
----
35.60
35.59
----
35.60
35.60
----
35.60
35.60
----
35.60
35.60
----
35.60
35.60
----

I am trying to eliminate repeat values every time the program loops and print to serial when there is a new value. As you can see, it thinks that 35.60 is not equal to 35.60.

This is really stumping me! :drooling_face: Thanks in advance!

Change
Serial.println(oldBaroin);
To
Serial.println(oldBaroin,4);

And see if they are still print equal values. One should avoid testing for equality of floating point variables as there are always gains of sands dropping/adding that make equality almost impossible to achieve. Convert to larger integer sizes and scale the units if you need large number ranges and testing for absolute equality between variables.

Lefty

Ah, I see. I looked at this: Math.round in Arduino - #7 by cmiyc - Programming Questions - Arduino Forum.

I then changed my code:

int oldCompareValue;
void loop() {
  // value is set up here by some sensors. It is a float
  
  float compareValueFloat= value * 100;
  int compareValue = round(compareValueFloat);  
  
  if (compareValue != oldCompareValue) {
  	  Serial.println(value, 4);
	  Serial.println(oldValue, 4);
  	  Serial.println("----");
    }
  oldCompareValue= compareValue;
}

It's now working splendidly! Thanks!

Another way to compare float variables is to take the positive difference between them and if that difference is less than some small value of your choice, consider them equal. Reverse the comparison to signal that they are different.

For example:

   if (abs(x-y) > 0.001) {
  //not equal, do something
   };