-1

1.I have tried to understand this code but I couldn't.would you help me?

    a = np.arange(5)
    hist, bin_edges = np.histogram(a, density=True)
    hist

2.why is the output like this ?

    array([0.5, 0. , 0.5, 0. , 0. , 0.5, 0. , 0.5, 0. , 0.5])
  • 1
    What don't you understand? `arange` or `historgram`? Have read the docs? Looked at `a` and `bin_edges`? – hpaulj Nov 16 '20 at 16:49

3 Answers3

0

The default for the bins argument to np.histogram is 10. So the histogram counts which bins your array elements fall into. In this case a = np.array([0, 1, 2, 3, 4]). If we are creating a histogram with 10 bins then we break the interval 0-4 (inclusive) into 10 equal bins. This gives us (note that 11 end points gives us 10 bins):

np.linspace(0, 4, 11) = array([0. , 0.4, 0.8, 1.2, 1.6, 2. , 2.4, 2.8, 3.2, 3.6, 4. ])

We now just need to see which bins your elements in the array a fall into. We can count them as follows:

[1, 0, 1, 0, 0, 1, 0, 1, 0, 1]

Now this is still not exactly what the output is. The density=True argument states (from the docs): "If True, the result is the value of the probability density function at the bin, normalized such that the integral over the range is 1."

Each bin (of height .5) has a width of .4 so 5 x .5 x .4 = 1 as is the requirement of this argument.

nick
  • 1,310
  • 8
  • 15
0

numpy.arange(5) generates a numpy array of 5 elements evenly spaced: array([0,1,2,3,4]). np.histogram(a, density=True) returns the bin edges and the values of an histogram obtained from your array a using 10 bins (which is the default value). bin_edges gives the edges of the bin, while histogram gives the number of occurrences for each bin. Given that you set density=True the occurrences are normalized (the integral over the range is 1.).

Look here for more information.

Moz-stack
  • 3
  • 1
-1

Please check this post. Hint: When you call np.histogram, the default bin value is 10, so that's why your output has 10 elements.

Diogo Silva
  • 320
  • 2
  • 14