Normalization of histogram in Octave by hist(y,x,norm)?

Viewed 429

I was trying to normalize the histogram of uniformly distributed random numbers in the interval [0,10]. In octave documentation I came across the function as hist(y, x, norm) which I applied and got the histogram normalized in the interval. The code that I used is

m=input('Number of random numbers required = ')
v=10*rand(1,m)
hist(v,10,1,"facecolor", "b", "edgecolor", "w",'linewidth',1.5);
title(['Normalized histogram for ' num2str(m) ' uniformly distributed random numbers'])
set(gca,'fontsize',30)

but as I changed the bin number to 50 then for getting the normalized histogram I had to change the third argument of hist() to 5. Here is the code

m=input('Number of random numbers required = ')
v=10*rand(1,m)
hist(v,50,5,"facecolor", "b", "edgecolor", "w",'linewidth',1.5);
title(['Normalized histogram for ' num2str(m) ' uniformly distributed random numbers'])
set(gca,'fontsize',30)

then only it produced a normalized histogram as the previous one. What's actually happening here? Why I need to change the norm argument to 5 when I changed the bin number to 50?

When I tried to normalize the gaussian distribution using same method I got it wrong ?( I had to do it write all the algorithm to get the correct answer) so I would like to know how the norm argument works ? here is the code that i tried for gaussian distribution which yielded the wrong result


m=input('Number of random numbers required = ');
v=randn(1,m)
[f,x]=hist(v,50);
hold on;
g = 1 / sqrt(2 * pi) * exp(-0.5 * x .^ 2);
plot(x, g, 'r','linewidth',1.5);
hist(v,50,5,"facecolor", "b", "edgecolor", "w",'linewidth',1.5);
title(['Normalized histogram for ' num2str(m) ' gaussian distributed random numbers'])
set(gca,'fontsize',30)
1 Answers

The reason is because you are trying to compare a frequency histogram with a frequency DENSITY function. Which means you have not taken the effect of the bin width into account.

In other words, if we consider each value in v, which represents histogram height, to be the product of the bin width w and a 'density' value h such that v = h * w at each element, then your normalisation says that sum(v) = 1, and therefore sum(h * w) = w * sum(h) = 1.

Therefore in order to obtain a valid 'density' function from your current values, you need to divide your current values in v by the (constant) bin width w, to obtain the density value h.

Compare with this code:

m       = 5000;
v       = randn( m, 1 );
g       = 1 / sqrt(2 * pi) * exp( -0.5 * x .^ 2 );
[nn,xx] = hist( v, 50, 1, 'facecolor', 'b', 'edgecolor', 'w', 'linewidth', 1.5);
nn      = nn / diff(xx)(1);

bar( xx, nn, 0.5, 'facecolor', [0, 0.5, 1], 'edgecolor', [0, 0.25, 0.5] );
hold on;
plot(x, g, 'r','linewidth', 3);
title({ ['Normalized histogram for ', num2str(m)], ' gaussian distributed random numbers'})
set(gca,'fontsize',20)
hold off
Related