Numpy average function rounding off error

2019-06-22 08:22发布

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条回答
狗以群分
2楼-- · 2019-06-22 09:02

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.

查看更多
登录 后发表回答