如何在 Python 中包含数学函数作为函数的参数?
在我的特殊情况下,我正在编写理想情况下的黎曼和计算器:
def riemann_sum(func_x, minvalue, maxvalue, partitions)
...
return riemannSum
其中 func_x 是 x 的某个函数,因此我可以找到任意函数的黎曼和:
func_x = x**2
minvalue = 1
maxvalue = 2
partitions = 100
a = riemann_sum(func_x,minvalue,maxvalue,partitions)
print(a)
但是,我无法执行上述过程,因为 x 未定义。
我可以通过手动将 x 的特定函数输入黎曼和来获取它,如下所示:
someList = [x**2 for x in someOtherList]
在这里,函数是 x**2,但如果不实际进入并更改函数,我无法更改它。
我现在唯一的解决办法是每次我想找到一个新函数的定积分时定义一个新的黎曼和函数,这个方法可行,但我觉得有更好的方法。
(编辑:我的问题与标记为可能重复的黎曼和问题不同。他们的问题是关于专门针对黎曼和的实现。我的问题是关于如何将数学函数合并为函数的参数,我碰巧用黎曼和作为一个特殊的例子)
请您参考如下方法:
在 Python 中,函数是第一类对象,因此您可以将函数作为参数传递给其他函数。也就是说,您编写 riemann_sum 函数声明的方式没有问题。
不起作用的是您对 func_x 的定义,因为您需要将 func_x 定义为一个函数。为此,您可以这样做:
func_x = lambda x: x**2
或者,对于更通用的多行(或单行)函数
def func_x(x):
temp = x**2 # just to stretch this out to another line for demonstration
return temp
然后你可以这样说:
def riemann_sum(func_x, minvalue, maxvalue, partitions):
# below just demos calling func_x, and is a bad way to do the sum
riemannSum = 0
step = 1.0*(maxvalue-minvalue)/partitions
value = minvalue
while value<maxvalue:
riemannSum == step*func_x(value) # here's where func_x is called
value += step
return riemannSum
也就是说,这里的重点是演示如何在riemann_sum 函数中调用func_x。这允许您根据计算总和所需的不同 x 值计算 func_x。
