Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy average function rounding off error

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)?

like image 695
Shishir Pandey Avatar asked Sep 04 '13 20:09

Shishir Pandey


People also ask

How is NP mean () different from NP average () in NumPy?

np. mean always computes an arithmetic mean, and has some additional options for input and output (e.g. what datatypes to use, where to place the result). np. average can compute a weighted average if the weights parameter is supplied.

How do I round up in NumPy?

You can use np. floor() , np. trunc() , np. ceil() , etc. to round up and down the elements of a NumPy array ndarray .

How do you find the mean of a column in NumPy?

You need to use Numpy function mean() with "axis=0" to compute average by column. To compute average by row, you need to use "axis=1". array([ 7., 8., 9., 10.])


1 Answers

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.

like image 151
Phillip Cloud Avatar answered Oct 14 '22 16:10

Phillip Cloud