Arduino Aggregation Error

Hello, I'm developing a project with arduino and I'm trying to adjust the frequency using a float, so I add and subtract 0.0025 value, but sometimes it adds 0.0026 instead of 0.0025, and on the contrary, it subtracts 0.0026 more in the subtraction process.


Welcome to the forum

Please follow the advice given in the link below when posting code, in particular the section entitled 'Posting code and common code problems'

Use code tags (the </> icon above the compose window) to make it easier to read and copy for examination

Sorry i added the codes like this

float minFrequency = 134.0000;
float maxFrequency = 174.0000;
float setFrequency = 144.8000;

void loop() {
  DrawScreen();

  btn1 = digitalRead(BTN_1);
  btn2 = digitalRead(BTN_2);
  btn3 = digitalRead(BTN_3);
  btn4 = digitalRead(BTN_4);

  // Yukarı Button
  if (btn1 == LOW && btn_prev_1 == HIGH) {
      if (menu_code == 2 && ((setFrequency + 0.0025L) <= maxFrequency)) {
      setFrequency += 0.0025L;
    }
  }
  

  // Sağ Button
  if (btn2 == LOW && btn_prev_2 == HIGH) {
    
  }

  // Aşağı Button
  if (btn3 == LOW && btn_prev_3 == HIGH) {
    if (menu_code == 2 && ((setFrequency - 0.0025L) >= minFrequency)) {
      setFrequency -= 0.0025L;
    }
  }

  // Sol Button
  if (btn4 == LOW && btn_prev_4 == HIGH) {
    
  }

  btn_prev_1 = digitalRead(BTN_1);
  btn_prev_2 = digitalRead(BTN_2);
  btn_prev_3 = digitalRead(BTN_3);
  btn_prev_4 = digitalRead(BTN_4);
}

What is this on, a Nano, a Uno, a Mega, ESP32, ???? It matters.

That is the standard problem with floating point math. On an AVR-based arduino, with 32 bit floats, you have slightly over six decimal digits of precision (call it six for demonstration purposes).

Add   174.0000
   +    0.0025
   =  174.0025

which is seven digits, the last one being unreliable. This will work on processors that actually handle type double, for 64 bit floats (not supported by Arduino Uno, Mega and the like).

Developed UNO but I'll use Pro Micro after it's finished

pro uses micro atmega32u4, will this be a problem?

The ATmega32u4 based Arduinos do not support type double. So you will see exactly the same problem.

The inaccuracies that accumulate when you add small numbers to large numbers is a classical problem in computing, and has been solved in many different ways.

One method is to keep track of the fraction to be added in terms of a separate integer. For example, instead of adding 0.0025 to 174 ten times, accumulating errors every time you add, simply add 0.025 (ten times the fraction) once.

In your case, it appears that you are calculating frequency channels. The obvious approach is to assign a channel number, then any given channel has
frequency = base_frequency + (channel_number)*step

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.