问题描述
我正在尝试使用 scipy.integrate.quad
将一个函数集成到 Python 中.这个特殊的函数有两个参数.我只想整合一个论点.示例如下所示.
There is a function I am trying to integrate in Python using scipy.integrate.quad
. This particular function takes two arguments. There is only one argument I want to integrate over. An example is shown below.
from scipy import integrate as integrate
def f(x,a): #a is a parameter, x is the variable I want to integrate over
return a*x
result = integrate.quad(f,0,1)
此示例不起作用(您可能很清楚),因为 Python 在我尝试时提醒我:
This example doesn't work (as is likely clear to you) since, as Python reminds me when I try it:
TypeError: f() takes exactly 2 arguments (1 given)
我想知道如何使用 integrate.quad()
在给定的函数通常是一个多变量函数时在单个变量意义上进行积分,额外的变量提供参数功能.
I am wondering how to use integrate.quad()
to integrate in a single variable sense when the function given is, in general, a multi-variable function, with the extra variables providing parameters to the function.
推荐答案
在 scipy 文档.
您可以执行以下操作:
from scipy import integrate as integrate
def f(x,a): #a is a parameter, x is the variable I want to integrate over
return a*x
result = integrate.quad(f,0,1,args=(1,))
quad
方法中的 args=(1,)
参数将使 a=1
用于积分计算.
The args=(1,)
argument in the quad
method will make a=1
for the integral evalution.
这也可以用于具有两个以上变量的函数:
This can also be carried to functions with more than two variables:
from scipy import integrate as integrate
def f(x,a,b,c): #a is a parameter, x is the variable I want to integrate over
return a*x + b + c
result = integrate.quad(f,0,1,args=(1,2,3))
这将使 a=1, b=2, c=3
用于积分计算.
This will make a=1, b=2, c=3
for the integral evaluation.
对于要以这种方式集成的函数,要记住的重要一点是将要集成的变量设置为函数的第一个参数.
The important thing to remember for the function you want to integrate this way is to make the variable you want to integrate over the first argument to the function.
这篇关于如何使用 Python 的 scipy.integrate.quad 评估多元函数的单积分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!