Invalid printed value

Hi,
I work on Arduino Uno and I’m a newbie.
I’m trying to build a binary file transfer with a Windows application. Looking at the frexp() function, I wrote:

#define _SERIAL_BAUDS   115200

#define _real_value     19116.434543
#define _precision      6

void setup() {
    Serial.begin(_SERIAL_BAUDS);
    while (!Serial) {;}
    
    double d = _real_value;
    double md;
    
    float f = _real_value;
    float mf;
    
    int n;
    
    // == float print
    mf = frexp(f, &n);
    Serial.print("f :"); Serial.print(f, _precision);Serial.println("");
    Serial.print("The mantissa is ");Serial.print(mf,_precision);Serial.print(" and the exponent is "); Serial.print(n); Serial.println("");
    Serial.print("Result :"); Serial.print(mf*pow(2,n),_precision);Serial.println("");
    Serial.println("");
    delay(100);
    
    // == double print
    md = frexp(d, &n);
    Serial.print("d :"); Serial.print(d,_precision);Serial.println("");
    Serial.print("The mantissa is ");Serial.print(md,_precision);Serial.print(" and the exponent is "); Serial.print(n); Serial.println("");
    Serial.print("Result :"); Serial.print(md*pow(2,n),_precision);Serial.println("");
    Serial.println("");
    delay(100);
}

void loop() {
  while (true) {delay(1000);}

}

And the output is (copy/paste) :

f :19116.433593
The mantissa islt :19116.433593

ponent is 15
Result :19116.433593

d :19116.433593
The mantissa is 0.583387 and the exponent is 15
Result :19116.433593

f :19116.433593
The mantissa is 0.583387 and the exponent is 15
Result :19116.433593

d :19116.433593
The mantissa is 0.583387 and the exponent is 15
Result :19116.433593

:o :o :o

Why if the decimal part of real value is define as 434543, the print and the used value is 433593 !?!?
Moreover, why the float print sequence is happening twice?

Any explanations?

Thanks !

On the Arduino Uno, double and float are the same (32 bits), and can accurately represent only 6-7 decimal digits.

For the number 19116.43... digits after ".43" are noise.

ok. Thanks! :slight_smile:

francesco_123:
Moreover, why the float print sequence is happening twice?

When you upload to an UNO, the new sketch runs for a little over 100 milliseconds before Serial Monitor connects and causes a reset. If you press the reset button on the Arduino it should only print once.
(I figured this out yesterday with a sketch that would increment a location in EEPROM. If there was no significant delay before the writing of EEPROM, the value would go up by 2 on an upload and 1 on a reset. Adding a 100-millisecond delay caused the increment to be sometimes 1 and sometimes 2 on an upload. Adding a 200-millisecond delay caused the increment to always be 1 on an upload.)

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