Floating point sum cannot exceed 16777216

silvioteston
Posts: 2
Joined: Thu Jun 13, 2024 9:35 pm

Floating point sum cannot exceed 16777216

Postby silvioteston » Sun Jun 23, 2024 4:11 pm

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?
Last edited by silvioteston on Fri Jun 28, 2024 2:08 pm, edited 1 time in total.

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

Re: Floating point sum cannot exceed 16777216

Postby ESP_Sprite » Mon Jun 24, 2024 1:55 am

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.

MicroController
Posts: 1702
Joined: Mon Oct 17, 2022 7:38 pm
Location: Europe, Germany

Re: Floating point sum cannot exceed 16777216

Postby MicroController » Mon Jun 24, 2024 8:24 am


silvioteston
Posts: 2
Joined: Thu Jun 13, 2024 9:35 pm

Re: Floating point sum cannot exceed 16777216

Postby silvioteston » Fri Jun 28, 2024 2:13 pm

Thank you very much! I ended up forgetting this "small" detail.

Who is online

Users browsing this forum: irahul and 95 guests