计算广义二项式定理分子的矢量化方法?

Vectorized approach for calculating numerator for generalized binomial theorem?

我正在尝试使用矢量化方法编写广义二项式定理,其中 n 可以是任何有理数。公式如下图所示。

每一项的分子为n, n×(n-1) , n×(n-1)×(n-2) 等等。我已将 0.5 分配给 n 并尝试生成 5 个术语。

到目前为止,我有一个分子乘积数组: [ 0.5 -0.5 -1.5 -2.5 -3.5] 使用

def num_products(number_of_terms):
    r = np.arange(1,number_of_terms+1)
    num_prod = np.array(n-r+1)
    return num_prod

但是想要为每个项创建一个分子数组,就像这样(数组中的每个项目以逗号分隔):

[ 0.5, 0.5×-0.5, 0.5×-0.5×-1.5, 0.5×-0.5×-1.5×-2.5, 0.5×-0.5×-1.5×-2.5×-3.5]

有谁知道如何使用数组(矢量化方法)来做到这一点?我正在努力使计算项的速度非常快,这样我就可以拥有更多的项并提高结果的准确性。

Formula for generalized binomial theorem

每个术语 x*(x-1)*(x-2)*...*(x - n + 1) 被称为 falling factorial. The wikipedia article also describes the rising factorial x*(x+1)*...*(x + n - 1). Some computational libraries include implementations of these. For example, mpmath has mpmath.ff and mpmath.rf

SciPy 将上升阶乘实现为 scipy.special.poch。下降阶乘可以根据上升阶乘来实现,如

from scipy.special import poch


def ff(x, m):
    return poch(x - m + 1, m)

因为 poch 是作为 NumPy“ufunc”实现的,它处理广播,因此 ff 也是如此。这意味着您可以为 m 传入一组值,一次调用即可计算出所有相应的下降阶乘。

例如,要获得 n = 0.5 的广义二项式的前六个分子项(包括初始项 1),请调用 ff(0.5, np.arange(6)):

In [38]: ff(0.5, np.arange(6))
Out[38]: array([ 1.     ,  0.5    , -0.25   ,  0.375  , -0.9375 ,  3.28125])

[1, 0.5, 0.5×-0.5, 0.5×-0.5×-1.5, 0.5×-0.5×-1.5×-2.5, 0.5×-0.5×-1.5×-2.5×-3.5]相同:

In [40]: [1, 0.5, 0.5*-0.5, 0.5*-0.5*-1.5, 0.5*-0.5*-1.5*-2.5, 0.5*-0.5*-1.5*-2.5*-3.5]
Out[40]: [1, 0.5, -0.25, 0.375, -0.9375, 3.28125]

所以如果你不介意对SciPy的依赖,你可以使用上面定义的ff来做你想做的事情。