首页 > 解决方案 > 是否有可以处理数组输入的python阶乘函数?

问题描述

我想计算 2 个变量的函数的值,其中一个变量用作阶乘的参数。

import numpy as np    
a = np.array([[1,2,3]]).T
b = np.array([[4,5,6]])

def f1(a,b):
    return a*b

def f2(a,b):
    return a*b / fact(b)

其中 fact(b) 是要定义的阶乘函数。

执行 f1 产生:

f1(a,b)
Out[112]: 
array([[ 4,  5,  6],
       [ 8, 10, 12],
       [12, 15, 18]])

这完全是我想要的结果形状。

如果我用 f2 之类的阶乘扩展函数,无论我使用什么阶乘函数,都会产生错误。

我尝试了一种迭代方式:

def fact(n):
fac = n
for i in range(1, n):
    fac *= i
return fac

a*b / fact(b)
TypeError: only integer scalar arrays can be converted to a scalar index

递归方式:

fact = lambda x: x * fact(x-1) if x > 1 else 1
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

或麻木的方式:

a*b / np.math.factorial(b)
TypeError: only size-1 arrays can be converted to Python scalars

没有一种方法能够以这种方式解释数组输入,计算更简单的函数 f1,即结果数组的每个元素都是使用输入数组的一个元素计算的(只是在某种程度上,2 个嵌套循环会做,我想避免)。

是否有任何阶乘函数可以将数组作为输入处理?

谢谢你,莱帕克

标签: pythonarraysnumpyfactorial

解决方案


推荐阅读