Math problem in ESP32?

Dremicon
Posts: 2
Joined: Sat Jun 29, 2024 9:41 pm

Math problem in ESP32?

Postby Dremicon » Sat Jun 29, 2024 9:46 pm

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
Attachments
fallo float.png
fallo float.png (31.89 KiB) Viewed 5165 times

ESP_Sprite
Posts: 9757
Joined: Thu Nov 26, 2015 4:08 am

Re: Math problem in ESP32?

Postby ESP_Sprite » 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.

Dremicon
Posts: 2
Joined: Sat Jun 29, 2024 9:41 pm

Re: Math problem in ESP32?

Postby Dremicon » Mon Jul 01, 2024 11:31 pm

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.

Who is online

Users browsing this forum: No registered users and 22 guests