Python 3.x python中梯形近似误差绘图
我正在尝试编写一个函数,该函数根据步长绘制复合梯形规则的误差 显然这看起来不太好,因为我刚刚开始学习这些东西 不管怎样,我设法得到了一个图和所有的东西,但是我应该得到一个坡度为2的图,所以我需要帮助来找出我哪里出了问题Python 3.x python中梯形近似误差绘图,python-3.x,Python 3.x,我正在尝试编写一个函数,该函数根据步长绘制复合梯形规则的误差 显然这看起来不太好,因为我刚刚开始学习这些东西 不管怎样,我设法得到了一个图和所有的东西,但是我应该得到一个坡度为2的图,所以我需要帮助来找出我哪里出了问题 from scipy import * from pylab import * from matplotlib import * def f(x): #define function to integrate
from scipy import *
from pylab import *
from matplotlib import *
def f(x): #define function to integrate
return exp(x)
a=int(input("Integrate from? ")) #input for a
b=int(input("to? ")) #inpput for b
n=1
def ctrapezoidal(f,a,b,n): #define the function ctrapezoidal
h=(b-a)/n #assign h
s=0 #clear sum1-value
for i in range(n): #create the sum of the function
s+=f(a+((i)/n)*(b-a)) #iterate th sum
I=(h/2)*(f(a)+f(b))+h*s #the function + the sum
return (I, h) #returns the approximation of the integral
val=[] #start list
stepsize=[]
error=[]
while len(val)<=2 or abs(val[-1]-val[-2])>1e-2:
I, h=ctrapezoidal(f,a,b,n)
val.append(I)
stepsize.append(h)
n+=1
for i in range(len(val)):
error.append(abs(val[i]-(e**b-e**a)))
error=np.array(error)
stepsize=np.array(stepsize)
plt.loglog(stepsize, error, basex=10, basey=10)
plt.grid(True,which="both",ls="steps")
plt.ylabel('error')
plt.xlabel('h')
从scipy导入*
从派拉布进口*
从matplotlib导入*
定义f(x):#定义要集成的函数
返回exp(x)
a=int(输入(“从中集成”)#a的输入
b=int(输入(“to?”)#b的输入
n=1
定义CtrapezoId(f,a,b,n):#定义函数CtrapezoId
h=(b-a)/n#分配h
s=0#清除sum1值
对于范围(n)中的i:#创建函数的和
s+=f(a+((i)/n)*(b-a))#迭代求和
I=(h/2)*(f(a)+f(b))+h*s#函数+和
return(I,h)#返回积分的近似值
val=[]#开始列表
步长=[]
错误=[]
而len(val)1e-2:
一、 h=ctrapezoidal(f,a,b,n)
val.append(I)
步长。追加(h)
n+=1
对于范围内的i(len(val)):
错误。追加(abs(val[i]-(e**b-e**a)))
error=np.array(错误)
步长=np.数组(步长)
plt.loglog(步长,错误,basex=10,basey=10)
plt.grid(True,which=“both”,ls=“steps”)
plt.ylabel('错误')
plt.xlabel('h')