How to compute sum of binomial more efficiently?

前端 未结 3 934
太阳男子
太阳男子 2020-12-20 09:22

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 fo

3条回答
  •  旧时难觅i
    2020-12-20 09:43

    rahnema1's answer has a very good approach: create a table of values that you generate once and access later (as well as some other clever optimizations).

    One thing I would change is the way the binomial coefficients are calculated. If you look at calculating the factorials for nchoosek(n, k) and nchoosek(n, k+1), you're recalculating n! both times, and for k+1, you're recalculating k! and multiplying it by k+1. (Similarly for (n-k)!.)

    Rather than throw away the computations each time, we can iteratively compute nchoosek(n, k+1) based on the value of nchoosek(n, k).

    function L=combList(n, maxk)
    % Create a vector of length maxk containing
    %   [nchoosek(n, 1), nchoosek(n, 2), ..., nchoosek(n, maxk)]
    % Note: nchoosek(n, 0) == nchoosek(n, n) == 1
    
    assert(maxk<=n, 'maxk must be less than or equal to n');
    
    L = zeros(1,maxk);
    L(1) = n;                    % nchoosek(n, 1) == n
    for k = 2:maxk
       L(k) = L(k-1)*(n-k+1)/k;
    end
    

    In your program, you would just create 3 lists for k1, k2, and k1+k2 with the appropriate limits, and then index into those lists to generate the sums.

提交回复
热议问题