Numpy average function rounding off error

空扰寡人 提交于 2020-01-14 09:58:07

问题


I find this very weird. Can someone tell me whats going on here?

>>>a = [1,0,1]
>>>np.mean(a)
   0.66666666666666663
>>>2.0/3
   0.6666666666666666

What's up with the 3 in the end of the output of np.mean(a)? Why isn't it a 6 like the line below it or a 7(when rounding off)?


回答1:


This is just a case of a different string representation of two different types:

In [17]: a = [1, 0, 1]

In [18]: mean(a)
Out[18]: 0.66666666666666663

In [19]: type(mean(a))
Out[19]: numpy.float64

In [20]: 2.0 / 3
Out[20]: 0.6666666666666666

In [21]: type(2.0 / 3)
Out[21]: float

In [22]: mean(a).item()
Out[22]: 0.6666666666666666

They compare equal:

In [24]: mean(a) == 2.0 / 3
Out[24]: True

In [25]: mean(a).item() == 2.0 / 3
Out[25]: True

Now might be the time to read about numpy scalars and numpy dtypes.



来源:https://stackoverflow.com/questions/18622795/numpy-average-function-rounding-off-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!