def Newton_Cotes (f, a, b, n): In=0 Coef = [0,[1./2,1./2], [1./6,4./6,1./6], [1./8,3./8,3./8,1./8], [7./90,32./90,12./90,32./90,7./90], [19./288,75./288,50./288,50./288,75./288,19./288], [41./840,216./840,27./840,272./840,27./840,216./840,41./840]] pas= (b-a) / n Wn= Coef[n] for k in range (n+1): In += Wn[k]*f(a+k*pas) In= In * (b-a) return In def NewtC_Comp (f, a, b, n, r): if n > 6: print ("n trop grand") else: Itot=0 pas= (b-a)/r X = [a+k*pas for k in range (r+1)] for k in range (r): Itot += Newton_Cotes(f,X[k],X[k+1],n) return Itot
f(x)= 1/(1+x**2) n= Newton_Cotes(f,-10,10,6) Iex=numerical_approx(arctan(10)-arctan(-10)) Iex
2.94225534860747
def NewtC_Comp1(f,a,b,r): Itot=0 pas= (b-a)/r X = [a+k*pas for k in range (r+1)] for k in range (r): Itot += Newton_Cotes(f,X[k],X[k+1],1) return Itot
NewtC_Comp(f,-10,10,2, 10)
2.86333198359790
Pts=[[] for i in range (6)] x="" for j in range (1,7): for k in range (1,21): Iapprox=NewtC_Comp(f,-10,10,j,k) err=abs(numerical_approx(Iex-Iapprox)) Pts[j-1].append((k,err)) line(Pts[0], color='red')+line(Pts[1],color='yellow')+line(Pts[2])+line(Pts[3])+line(Pts[4])+line(Pts[5],color='black')
def Legendre(n): L=[1,x] for k in range (2,n): Pk = ((2*k-1)*x*L[k-1] - (k-1)*L[k-2]) / (k) L.append(Pk) return L
def Racines(L,n): Racine=[] X = srange(-1,1.1,0.1) Intervalle=[] for i in range (len(X)-1): if (L[n](X[i]) * L[n](X[i+1])) < 0: Intervalle.append([X[i],X[i+1]]) '''for j in range Intervalle: Racine.append(Racine_newt(L[n],i[0],10))''' for j in range (len(Intervalle)): Racine.append(Racine_Newt(L[n], (Intervalle[j][0]+Intervalle[j][1])/2, 10)) return Racine def Racine_Newt (fa, x0, m): dfa=diff(fa,x) phi(x)=x-fa(x)/dfa(x) xn=x0 while abs(xn-phi(xn)) > 10**(-m): xn=phi(xn) return phi(xn)
n=4 L=Legendre(n) XX=[] for k in range(2,n): XX.append(Racines(L,k)) XX
[[-0.577350269189626, 0.577350269189626], [-0.774596669241483, 0.000000000000000, 0.774596669241483]]
def Poids(A): W=[] for n in range(4): Pn(x)=L[n+1] dPn=diff(Pn,x) W.append(1/(1-xk**2)*dPn(xk)**2) return W def Gauss_L (f,a,b,n,W): for i in range(2,n): P += W[i]*f(xk) P= 2*P