如何在Python中包含数学函数作为函数的参数?
在我的特定情况下,我正在编写一个理想的Riemann和计算器:
def riemann_sum(func_x, minvalue, maxvalue, partitions)
...
return riemannSum
其中func_x是x的某个函数,因此我可以找到以下任意函数的riemann和:
func_x = x**2
minvalue = 1
maxvalue = 2
partitions = 100
a = riemann_sum(func_x,minvalue,maxvalue,partitions)
print(a)
但是,我无法执行上述过程,因为x是未定义的。
通过将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
也就是说,这里的要点是演示如何func_x
在riemann_sum
函数内调用。这样,您就可以func_x
根据需要求和以不同的x值求值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句