将下面的matlab代码变成python代码
时间: 2023-07-10 20:32:56 浏览: 45
下面是Matlab代码:
```matlab
% Define the function
f = @(x) sin(x);
% Define the limits of integration
a = 0;
b = pi/2;
% Define the number of subintervals
n = 10;
% Calculate the width of each subinterval
h = (b - a)/n;
% Calculate the values of the function at each subinterval
x = a:h:b;
y = f(x);
% Calculate the area using the trapezoidal rule
area = h*(sum(y) - (y(1) + y(end))/2);
```
下面是对应的Python代码:
```python
import math
# Define the function
def f(x):
return math.sin(x)
# Define the limits of integration
a = 0
b = math.pi/2
# Define the number of subintervals
n = 10
# Calculate the width of each subinterval
h = (b - a)/n
# Calculate the values of the function at each subinterval
x = [a + i*h for i in range(n+1)]
y = [f(x[i]) for i in range(n+1)]
# Calculate the area using the trapezoidal rule
area = h*(sum(y) - (y[0] + y[-1])/2)
```
请注意,Python中的列表索引从0开始,因此需要将y(1)和y(end)替换为y[0]和y[-1]。此外,需要导入math模块以使用sin函数。