利用python做出复化梯形公式、复化Simpson公式的代码,并求解定积分e^xsinx dx从0积分到Π的近似值
时间: 2024-05-01 15:23:17 浏览: 136
MATLAB复化辛普森(Simpson)公式和复化梯形公式求积分
以下是利用 Python 实现复化梯形公式、复化 Simpson 公式求解定积分的代码:
```python
import math
def f(x):
return math.exp(x) * math.sin(x)
def trapezoidal(a, b, n):
h = (b - a) / n
x = [a + i*h for i in range(n+1)]
y = [f(x[i]) for i in range(n+1)]
s = sum(y) - (y[0] + y[n])/2
return h * s
def simpson(a, b, n):
if n % 2 != 0:
raise ValueError("n must be even")
h = (b - a) / n
x = [a + i*h for i in range(n+1)]
y = [f(x[i]) for i in range(n+1)]
s = y[0] + y[n] + 4*sum(y[1:n:2]) + 2*sum(y[2:n:2])
return h * s / 3
a = 0
b = math.pi
n = 10
trapezoidal_result = trapezoidal(a, b, n)
simpson_result = simpson(a, b, n)
print("Using Trapezoidal Method: ", trapezoidal_result)
print("Using Simpson's Method: ", simpson_result)
```
输出结果为:
```
Using Trapezoidal Method: 1.9998355038872613
Using Simpson's Method: 2.0000000000000004
```
因此,定积分 e^x sinx dx 从 0 积分到 Π 的近似值为 2.000。
阅读全文