本文介绍了对于二项式函数nCr = k,给定r和k,求n的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个可以解决以下问题的函数:对于二项式函数nCr = k,在给定r和k的情况下找到n.在数学中nCr = n!/r!(n-r)! 我试过以下方法,但无法解决问题.例如8C6 = 28,对于我的函数,输入是6和28,我想找到8.这可能没有确切的整数,所以我想找到x> = n.

I need a function that can solve the following: for a binomial function nCr=k, given r and k find n. in mathematics nCr=n!/r!(n-r)! I tried following but it doesn't solve it. for example 8C6=28, for my function the inputs are 6 and 28 and i want to find 8. This may not have exact integer number so I want to find an x>=n.

"""I am approaching it this way, i.e. find the solution of a polynomial function iteratively, hope there is a better way"""
def find_n(r,k):
    #solve_for_n_in(n*(n-1)...(n-r)=math.factorial(r)*k
    #in the above example solve_for_n(n*(n-1)(n-2)(n-3)(n-4)(n-5)=720*28)

    sum=math.factorial(r)*k
    n=r+1
    p=1

    while p<sum:
        p=1
        for i in range(0,r+2):
            p*=(n-i)
        n+=1
    return n-1

谢谢.

推荐答案

以下是使用fminsearch的解决方案.您需要最小化nchoosek(n, r)k之间的绝对差.但是,您可能会遇到nchoosek的未定义值,因此最好从头开始定义它.不过也不要使用factorial,因为对于负整数它是未定义的.相反,请使用gamma(如果您不知道,请在Wikipedia上了解此内容).

Here's a solution which uses fminsearch. You'll want to minimize the absolute difference between nchoosek(n, r) and k. However, you'll likely run into undefined values for nchoosek, so it's better to define it from scratch. Don't use factorial either though, as it's undefined for negative integers. Instead, use gamma (read about this on Wikipedia if you don't know).

r = 6;
k = 28;
toMinimize = @(n) abs(gamma(n+1) / (gamma(r+1) * gamma(n-r+1)) - k);

要对初始条件保持警惕:

Be smart about the initial conditions:

for n = 1:10
    [res(n, 1), fval(n, 1)] = fminsearch(toMinimize, n);
end
[res fval]

现在您将看到您应该只信任初始条件n0 >= 5,答案是n = 8.

Now you'll see you should only trust initial conditions n0 >= 5, for which the answer is n = 8.

ans =
             1.42626953125          27.9929874410369
             1.42626953125          27.9929874410369
           3.5737060546875          27.9929874410073
             3.57373046875          27.9929874410369
                         8                         0
          8.00000152587891       5.2032510172495e-05
          8.00000152587891      5.20325100552554e-05
                         8                         0
          7.99999694824218      0.000104064784270719
                         8                         0

这篇关于对于二项式函数nCr = k,给定r和k,求n的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 22:48