0

Why are (big) values being changed?

I tried out printing some values and noticed bigger values are changed more, they seem to be rounded to quarters and then to halves when the value gets bigger.

MWE

void setup() {
  Serial.begin(9600);
  Serial.print("12457591.51 is changed into ");
  Serial.println(12457591.51);
  Serial.print("2457591.80 is changed into ");
  Serial.println(2457591.80);
  Serial.print("1234567.89 is changed into ");
  Serial.println(1234567.89);
}

void loop() {}

gives me

12457591.51 is changed into 12457592.00
2457591.80 is changed into 2457591.75
1234567.89 is changed into 1234567.87

I'm working with an Arduino Nano ATMega328.

Background I need the calculation (2457591.33 + 0.5 - 2440588) * 60 * 60 * 24 to be precise to within preferably a hundred, but currently it's off by about 7000.

PHPirate
  • 117
  • 1
  • 10

1 Answers1

1

Floating point numbers doesn't have infinite precision. But you can always change your equation to use smaller numbers (preferably integers or longs as floating point is extremely slow)

For example on AVR Freaks they mentioned precision about 6 or 7 digits. It makes sense as 24bits signed number range is from -8388608 to 8388607

KIIV
  • 4,742
  • 1
  • 12
  • 21
  • Of course they don't have infinite precision, but floats should have precision after the dot, right? I thought that's where floats were for. I don't mind speed at all but I understand ints or longs are better, so I'll try to convert the calculation to use longs. Do I understand correctly that the answer is that floats do not have precision when working with more than say 6 digits? – PHPirate Jul 21 '16 at 17:52
  • Only small numbers have some precision after the dot. Big ones doesn't have precision even before the dot. – KIIV Jul 21 '16 at 18:02
  • Saw your edit, that makes sense, hadn't thought of that. Thanks! – PHPirate Jul 21 '16 at 18:02