import numpy as np import math from scipy import integrate def f(x): return math.sin(x)*math.sin(x) #复化梯形法 def func(a,b,n,f): x = np.linspace(a,b,n+1) sum1 = 0 h =(b-a)/n for i in range(补充代码1): 补充代码2 return sum1 #复化辛普森法 def func1(a,b,n,f): x = np.linspace(a,b,n+1) sum1 = 0 h =(b-a)/n for i in range(补充代码3): 补充代码4 return sum1 #复化科特斯法 def func2(a,b,n,f): x = np.linspace(a,b,n+1) sum1 = 0 h =(b-a)/n for i in range( 补充代码5 ): 补充代码6 return sum1 answer = func(0,1,100,f) answer1 = func1(0,1,100,f) answer2 = func2(0,1,100,f) print(answer,answer1,answer2) #integrate积分作为精确值 value, error = integrate.quad(f,0, 1) print(value,error) print("error: ", abs(answer-value), abs(answer1-value), abs(answer2-value))import numpy as np import matplotlib.pyplot as plt plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文 标签 plt.rcParams['axes.unicode_minus']=False #用来正常显示负号 f=lambda x:np.sin(x)*np.sin(x) #向前差商 def fo_df(x,h): plt.plot([x-h,x],[f(x-h),f(x)],'r--',label='前') result= 补充代码7 return result #向后差商 def back_df(x,h): plt.plot([x,x+h],[f(x),f(x+h)],'k--',label='后') result= 补充代码8 return result#中心差商 def cen_df(x,h): a=(f(x-h)+f(x+h))/2 plt.plot([x-h,x+h],[f(x-h)+f(x)-a,f(x+h)+f(x)-a],'g--',label='中') result= 补充代码9 return result xx=np.linspace(-0.5,1.5,20) yy=f(xx) plt.plot(xx,yy) print('前',fo_df(0.5,0.5)) print('后',back_df(0.5,0.5)) print('中',cen_df(0.5,0.5)) plt.legend(loc='best') plt.show() xx=np.linspace(-1,1,20) yy=f(xx) plt.plot(xx,yy) print('前',fo_df(0.5,0.25)) print('后',back_df(0.5,0.25)) print('中',cen_df(0.5,0.25)) plt.legend(loc='best') plt.show()
时间: 2023-08-10 20:07:03 浏览: 186
代码中有一些没有补充的部分,我来帮你补充一下。
复化梯形法:
```python
def func(a,b,n,f):
x = np.linspace(a,b,n+1)
sum1 = 0
h =(b-a)/n
for i in range(n):
sum1 += (f(x[i])+f(x[i+1]))*h/2
return sum1
```
复化辛普森法:
```python
def func1(a,b,n,f):
x = np.linspace(a,b,n+1)
sum1 = 0
h =(b-a)/n
for i in range(n):
sum1 += h/6*(f(x[i])+4*f((x[i]+x[i+1])/2)+f(x[i+1]))
return sum1
```
复化科特斯法:
```python
def func2(a,b,n,f):
x = np.linspace(a,b,n+1)
sum1 = 0
h =(b-a)/n
for i in range(n//2):
sum1 += h/3*(f(x[2*i])+4*f((x[2*i]+x[2*i+1])/2)+f(x[2*i+1]))
return sum1
```
向前差商:
```python
def fo_df(x,h):
plt.plot([x-h,x],[f(x-h),f(x)],'r--',label='前')
result= (f(x)-f(x-h))/h
return result
```
向后差商:
```python
def back_df(x,h):
plt.plot([x,x+h],[f(x),f(x+h)],'k--',label='后')
result= (f(x+h)-f(x))/h
return result
```
中心差商:
```python
def cen_df(x,h):
a=(f(x-h)+f(x+h))/2
plt.plot([x-h,x+h],[f(x-h)+f(x)-a,f(x+h)+f(x)-a],'g--',label='中')
result= (f(x+h)-f(x-h))/(2*h)
return result
```
阅读全文