espressif / arduino-esp32

Arduino core for the ESP32
GNU Lesser General Public License v2.1
13.32k stars 7.36k forks source link

Floating points don't behave as expected #1546

Closed timkoers closed 6 years ago

timkoers commented 6 years ago

Hardware:

Board: Node32S Core Installation/update date: 28-06-2018 IDE name: Arduino IDE 1.8.5 Flash Frequency: 80Mhz Upload Speed: 921600

Description:

I am working with floats for the first time within the ESP-32 environment and it is not working as expected.

I am having issues with the results of sscanf and of floating point maths.

When changing the formatter to %.3f for example, the value of temp is 0.00.

I also tried using a %Lf and assigning the value to a double, without usable results.

Sketch:


#include <Arduino.h>

void setup() {
  Serial.begin(115200);
  float temp;
  sscanf("1-0:1.8.0*255(0003845.244*kWh)", "1-0:1.8.0*255(%f*kWh)", &temp);
  Serial.println(temp);

  float first = 3845.26;
  float second = 3845.27;

  Serial.println(second - first);
}

Debug Messages:

 Serial output of my code:

 3845.24
 0.00
lbernstone commented 6 years ago

Works fine for me. I don't think arduino is doing anything to simple math, so this should fall to your compiler. Can you try adding a Serial.printf("%f",second-first); to see if it is a precision problem?

timkoers commented 6 years ago

It has to do with the precision, I multiplied that value by 1000 and something showed up in the Serial monitor. Might be a nice change in the Serial.println()