1

I came across a problem where program added a float value to a long variable and result got completely wrong:

 float toadd = 30548.0f;
 long x1 = 1578726070000L;
 long x1old= x1;
 x1 += toadd;
 Log.d("TEST", "X1=" + x1old + " X1+=" + x1 + " Added:" + toadd + " Delta=" + (x1 - x1old));

The Logcat showed then:

TEST: X1=1578726070000 X1+=1578726064128 Added:30548.0 Delta=-5872

I know that mixing float and long is tricky and should be avoided, but still, how comes that adding a value actually made the receiving variable decrease, and with a 'random' figure on top?

michaelsmith
  • 1,011
  • 1
  • 16
  • 35
  • What @user85421 is saying is that the addition did not decrease the value. The conversion from long -> float that happened before the addition did. And that is because your long cannot be represented exactly as a float, so the conversion needs to round to the nearest possible value. – Thilo Jan 11 '20 at 08:35
  • 1
    To polish the notes above, IEEE floats have 23 bits of mantissa, so the maximum integer that can be represented precisely is ~8 million. The computation 1578726070000L + 30548.0f produces a float. If the float didn't have limited precision, this would be 1578726100548. In binary this is 0b10110111110010011011010001000111001000100. But the closest actual float is 0b10110111110010011011010 * 2^18. The last 18 bits are effectively set to zero because they don't exist at all. This is how the value decreases. The truncated bits have decimal value 36420. 36420 - 30548 = 5872. – Gene Jan 11 '20 at 09:03

0 Answers0