Page 1 of 1

Math problem in ESP32?

Posted: Sat Jun 29, 2024 9:46 pm
by Dremicon
Hello. Why when performing the following mathematical operation with float, the result is -0.0?
I don't make sense of the "-" sign. Is it a bug?
In the following code you can see the result:

Code: Select all

float val1 = -0.1;
float val2;

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

void loop(){
val2 = val1 + 0.1;
Serial.println(val2);
}
The result is -0.00

Re: Math problem in ESP32?

Posted: Mon Jul 01, 2024 9:07 am
by ESP_Sprite
Float numbers are imprecise; probably the result of 0.1 + -0.1 is ever-so-slightly negative because of effectively a binary rounding error. Your print will round that number down to two digits after the decimal, so you get the 'weird' -0.00 result.

Re: Math problem in ESP32?

Posted: Mon Jul 01, 2024 11:31 pm
by Dremicon
ESP_Sprite wrote:
Mon Jul 01, 2024 9:07 am
Float numbers are imprecise; probably the result of 0.1 + -0.1 is ever-so-slightly negative because of effectively a binary rounding error. Your print will round that number down to two digits after the decimal, so you get the 'weird' -0.00 result.
OK. Thanks for your reply.