Assume we do an experiment where we throw n balls into n jars. X is an independent variable describes number of balls int the first jar. Build a function returns the smallest integer fulfills P(X>m)<1/n^2.
The distribution is binomial so I wrote the following matlab function:
function m = intpq3(n)
flag=0;
par=1/n^2;
m=0;
P=0;
%Since X is non-neative integer
if(n==1)
m=-1*Inf;
else
while(flag==0 && m<=n)
m=m+1;
P=P+nchoosek(n,m)*(1/n)^m*(1-1/n)^(n-m);
if(1-P<=par)
flag=1;
end
end
end
disp(m)
end
But for every 'n' I give it, it returns either error or n-1. What am I doing wrong?
The following version of your program seems to do what you want. The problem with your version as far as I can tell is that you did not include
m=0
into your sum ofP
, thus1-P
was consistently too large. It's always a good idea to ask the program to spit out numbers and compare to paper-and-pencil calculations.The following also helped to diagnose the problem. It shows values of P(X>m) (colored dots) for different
m
at select values ofn
. Overlayed as a dashed line is1/n^2
.