3

I'm not sure if it is a bug or not. In below code, I got [0.0, 0.0, 0.1] and [0.0, 0.1, 0.1] as output, which are different. But I expected that both of the 2 print() output [0.0, 0.1, 0.1]

import numpy as np
print([round(x,1) for x in np.array([0.049, 0.05, 0.0501])])
print([round(x,1) for x in [0.049, 0.05, 0.0501]])
H42
  • 725
  • 2
  • 9
  • 28
  • I'd read the notes in: https://numpy.org/doc/stable/reference/generated/numpy.around.html, specifically the area talking about the difference between numpy's rounding and Python's built-in rounding. – alkasm Nov 02 '20 at 00:21
  • @alkasm Both numpy and Python3 are rounding a half to the nearest even number. The numpy behaviour is therefore understandable, but the Python behaviour is not, at least to me. The question to ask is why `round(0.05, 1) != 0`? – zvone Nov 02 '20 at 00:26
  • 1
    @zvone Because of floating point approximations. 0.05 is not exactly 0.05. – khelwood Nov 02 '20 at 00:36
  • @khelwood Yeah, figured that out, but why does it work with numpy? Does it have some smart way to detect that 0.05 is actually 0.05 and not 0.0500000000something? – zvone Nov 02 '20 at 00:47
  • 1
    The duplicate is not appropriate here. That question is about round-half-to-even. round-half-to-even isn't really relevant here, because `0.05` is not an exact tie. – Mark Dickinson Nov 02 '20 at 13:42
  • 1
    @zvone: NumPy is doing the naive thing of multiplying by `10`, rounding to the nearest integer, and dividing by `10` again. The multiplication by `10` incurs a rounding error which has the lucky (or unlucky, depending on your viewpoint) side-effect of turning something that wasn't an exact tie into something that _is_ an exact tie. Python is doing a correct rounding based on the exact value of the input (so here, `0.05000000000000000277555756156289135105907917022705078125`). – Mark Dickinson Nov 02 '20 at 14:35
  • @MarkDickinson Thanks, that is the info I was looking for. Do you know, is that documented somewhere? I could not find it. – zvone Nov 03 '20 at 17:35
  • @zvone Sorry, I don't know if it's documented. I got my information by looking at the source. – Mark Dickinson Nov 05 '20 at 19:24

0 Answers0