Page 1 of 1

Floating point sum cannot exceed 16777216

Posted: Sun Jun 23, 2024 4:11 pm
by silvioteston
In my source code, a float variable is used to hold the integral value of a signal read from A/D. This value remains constant for a long time, so the accumulated value in the float variable is expected to be considerably large.
The problem is that when I reach the value 16777216 the sum cannot go further, and is locked at this value.
I'm using ESP32-WROOM-32D and ESP-IDF 5.2.1.
An example code to reproduce the problem could be:

Code: Select all

float test = 0.0f;
int i = 0;
while (test < 123456789.0f)
{
	test += 0.8f;
	if (++i > 100000)
	{
		ESP_LOGI(TAG, "test=%0.2f", test);
		i = 0;
	}
}
Isn't the maximum float value 3.402823466E+38 ?
It's very strange, if you change the line test += 0.8f; the sum gets stuck in other values.
If I load a value like 123456890.0f into the float variable, it will represent something like 123456792.0f, which I'm okay with. Why when I make successive sums the float variable can't exceed the value 16777216?
Is it some hardware configuration or some limitation of the ESP32 or am I forgetting some understanding about the floating point representation?

Re: Floating point sum cannot exceed 16777216

Posted: Mon Jun 24, 2024 1:55 am
by ESP_Sprite
Floating point numbers are expressed as a 24-bit number with an 8-bit exponent: e.g. 1/2 would be stored as 0x1000000*(2^-25) = 1*(1/2) = 0.5. In your case: 16777216 would stored as 0x1000000*(2^0). That number has a precision of 1, in other words, it cannot represent anything after the decimal point anymore. If you add something less than 0.5 to it, the number remains the same.

Solution is to either use a double instead of a float (which uses 2x the memory so it can express numbers more precisely) or rework your code so it uses integers.

Re: Floating point sum cannot exceed 16777216

Posted: Mon Jun 24, 2024 8:24 am
by MicroController

Re: Floating point sum cannot exceed 16777216

Posted: Fri Jun 28, 2024 2:13 pm
by silvioteston
Thank you very much! I ended up forgetting this "small" detail.