I must calculate an equation as follows:
where k1,k2
are given. I am using MATLAB to compute P
. I think I have a correct implementation for the above equation. However, my implementation is so slow. I think the issue is from binomial coefficient. From the equation, could I have an efficient way to speed up the time? Thank all.
For k1=150; k2=150; D=200;
, it takes 11.6 seconds
function main
warning ('off');
function test_binom()
k1=150; k2=150; D=200; P=0;
for i=0:D-1
for j=0:i
if (i-j>k2||j>k1)
continue;
end
P=P+nchoosek(k1,j)*nchoosek(k2,i-j)/nchoosek((k1+k2),i);
end
end
end
f = @()test_binom();
timeit(f)
end
Update: For measure time, I found that nchoosek is the reason for large computational time. Hence, I rewrite the function as follows
function re=choose(n, k)
if (k == 0)
re=1;
else
re=(n * choose(n - 1, k - 1)) / k;
end
end
Now, the computational time is reduced as 0.25 second. Is has any better way?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…