1

Why does np.arange(5, 60, 0.1)[150] yield 19.999999999999947. But np.arange(5, 60, 0.5)[30] yield 20.0?

Why does this happen?

MSeifert
  • 145,886
  • 38
  • 333
  • 352
Lucidnonsense
  • 1,195
  • 3
  • 13
  • 35
  • This might help: http://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate In your case, 0.5 has an exact binary representation as a floating point number but 0.1 does not. – xnx Feb 12 '16 at 12:15

1 Answers1

1

That's because floats (most of the time) cannot represent the exact value you put in. Try print("%.25f" % np.float64(0.1)) which returns 0.1000000000000000055511151 that's not exactly 0.1.

Numpy already provides a good workaround for almost-equal (floating point) comparisons: np.testing.assert_almost_equal so you can test by using np.testing.assert_almost_equal(20,np.arange(5, 60, 0.1)[150]).

The reason why your second example provides the real valus is because 0.5 can be represented as exact float 2**(-1) = 0.5 and therefore multiplications with this value do not suffer from that floating point problem.

MSeifert
  • 145,886
  • 38
  • 333
  • 352