python求定积分:quad函数
文章目录
-
- 示例
- 完整参数
- weight参数
示例
quad是scipy.integrate中最常用的积分函数,示例如下
import numpy as np from scipy.integrate import quad func = lambda x: x**2 quad(func, 0, 4) # (21.333333333333332, 2.3684757858670003e-13) quad(np.sin, 0, np.pi) # (2.0, 2.220446049250313e-14)
在上面的代码中,func为待积分函数,后面紧跟着的两个参数表示积分的下界和上界。返回值有二,分别为积分结果和计算误差。
用于测试的两个函数的解析形式如下,可见计算结果吻合。
∫
0
4
x
2
d
x
=
1
3
x
3
∣
0
4
=
64
3
≈
21.3
∫
0
π
sin
x
d
x
=
−
cos
x
∣
0
π
=
2
\int_0^4 x^2\text dx=\frac{1}{3}x^3\big|^4_0=\frac{64}{3}\approx 21.3\\ \int^\pi_0\sin x\text dx=-\cos x\big|^\pi_0=2
∫04x2dx=31x3
04=364≈21.3∫0πsinxdx=−cosx
0π=2
完整参数
quad的完整参数如下
scipy.integrate.quad(func, a, b, args=(), full_output=0, epsabs=1.49e-08, epsrel=1.49e-08, limit=50, points=None, weight=None, wvar=None, wopts=None, maxp1=50, limlst=50, complex_func=False)
其中,
- args为func函数中,除待求积分参数之外的其他参数
- epsabs, epsrel 分别为绝对和相对误差
- limit 自适应算法中子区间的个数
- points 断点位置
- weight, wvar 定义域区间内的权重类型和权重
- wopts, maxp1 切比雪夫矩及其上限
weight参数
其中,weight和wvar参数的具体取值如下。
| weight | wvar | 函数 |
|---|---|---|
| “cos” |
w w w | cos w x \cos wx coswx |
| “sin” | w w w | sin w x \sin wx sinwx |
| “alg” | α , β \alpha, \beta α,β | g ( x ) g(x) g(x) |
| “alg-loga” | α , β \alpha, \beta α,β | g ( x ) log ( x − a ) g(x)\log(x-a) g(x)log(x−a) |
| “alg-logb” | α , β \alpha, \beta α,β | g ( x ) log ( b − x ) g(x)\log(b-x) g(x)log(b−x) |
| “alg-log” | α , β \alpha, \beta α,β | g ( x ) log ( x − a ) log ( b − x ) g(x)\log(x-a)\log(b-x) g(x)log(x−a)log(b−x) |
| “cauchy” | c c c | 1 x − c \frac{1}{x-c} x−c1 |
其中,
g
(
x
)
=
(
x
−
a
)
α
∗
(
b
−
x
)
β
g(x)=(x-a)^\alpha*(b-x)^\beta
g(x)=(x−a)α∗(b−x)β
设func为
f
(
x
)
=
x
f(x)=x
f(x)=x,若weight参数为cos,而wvar取值为
w
w
w,则实际计算的积分表达式为
∫
a
b
cos
w
f
(
x
)
d
x
\int_a^b\cos wf(x)\text dx
∫abcoswf(x)dx
示例如下
func = lambda x : x quad(func, 0, np.pi) # (4.934802200544679, 5.478731025015592e-14) quad(func, 0, np.pi, weight='cos', wvar=1) # (-1.9999999999999993, 1.926079284799239e-13)
本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://net2asp.com/fd73b015b8.html
