问题:求
∫
a
b
f
(
x
)
d
x
\int_a^b {f(x)}dx
∫abf(x)dx
辛普森积分的本质思想是将
f
(
x
)
f(x)
f(x)看作一个二次函数来简化问题
令
∫
a
b
f
(
x
)
d
x
≈
∫
a
b
(
A
x
2
+
B
x
+
C
)
d
x
\int_a^b f(x)dx\approx\int_a^b(Ax^2 + Bx + C)dx
∫abf(x)dx≈∫ab(Ax2+Bx+C)dx
即:
f
(
x
)
≈
A
x
2
+
B
x
+
C
f(x)\approx Ax^2+Bx+C
f(x)≈Ax2+Bx+C
可以解得:
∫
a
b
f
(
x
)
d
x
≈
(
b
−
a
)
6
∗
[
f
(
a
)
+
4
∗
f
(
a
+
b
2
)
+
f
(
b
)
]
\int_a^bf(x)dx\approx \frac{(b - a)}{6} *[f(a)+4*f(\frac{a+b}{2})+f(b)]
∫abf(x)dx≈6(b−a)∗[f(a)+4∗f(2a+b)+f(b)]
因为
∣
b
−
a
∣
|b-a|
∣b−a∣越小,误差越小,所以可以递归处理该问题
因为:
∫
a
b
f
(
x
)
d
x
=
∫
a
c
f
(
x
)
d
x
+
∫
c
b
f
(
x
)
d
x
\int_a^b f(x)dx=\int_a^cf(x)dx + \int_c^bf(x)dx
∫abf(x)dx=∫acf(x)dx+∫cbf(x)dx
至于精度问题,由误差分析的知识可得:(
ε
\varepsilon
ε为精度误差)
令
c
=
a
+
b
2
c=\frac{a+b}{2}
c=2a+b,
∣
∫
a
c
f
(
x
)
d
x
+
∫
c
b
f
(
x
)
d
x
−
∫
a
b
f
(
x
)
d
x
∣
<
=
15
ε
|\int_a^cf(x)dx+\int_c^bf(x)dx-\int_a^bf(x)dx| <= 15\varepsilon
∣∫acf(x)dx+∫cbf(x)dx−∫abf(x)dx∣<=15ε
时即可返回;
注意: 每次递归的时候由于误差的相加性,误差设置必须变为原来的一半
C o d e Code Code
inline double f(double x){
//...
}
inline double simpson(double a, double b){
return (f(a) + f(b) + 4 * f((a + b) / 2) ) * (b - a) / 6;
}
double asr(double a, double b, double eps, double A){ //A为a,b区间的积分
double c = (a + b) / 2;
double l = simpson(a, c), r = simpson(c, b);
if (fabs(l + r - A) <= 15 * eps) return l + r + (l + r - A) / 15.0;
return asr(a, c, eps / 2.0, l) + asr(c, b, eps / 2.0, r);
}