python - 是否有可以处理数组输入的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 个嵌套循环会做,我想避免)。
是否有任何阶乘函数可以将数组作为输入处理?
谢谢你,莱帕克
解决方案
推荐阅读
- ssl - mitmproxy:禁用 SSL-ed 内容检查,但处理其余内容
- python - 在 GitHub Pages 上显示交互式绘图图表(.html 文件)
- javascript - 数组中的对象未在 JavaScript 中更新
- c# - 将配置值作为参数传递给实例方法 C#
- reactjs - 如何在 useEffect 中向 useRef 添加事件侦听器
- flask - Vuetify - 我如何将单选按钮值保存在变量中
- python - Django 返回 format_html
- java - 在模拟器上运行 android 应用程序时出现 GRPC 服务器错误
- python - 运行 tflite 模型时出现问题(tflite 模型的结果是 nan)
- sql - Oracle SQL 分区依据以选择最近的日期