import matplotlib.pyplot as plt import numpy as np from math import * def f(x): return cos(x)-x def fp(x): return -sin(x)-1 def iteration_dichotomie(a,b,m,epsilon,f): def maj_test(xn,xnm1): return f(xn) != 0 and abs(xnm1-xn) > epsilon xnm1 = a xn= a X=[] n = 1 an= a bn=b test = True while n <= m and test: xnm1 = xn xn=float(an+bn)/2 test = maj_test(xn,xnm1) X +=[xn] if f(an)*f(xn)<=0 : bn=xn else : an=xn n +=1 return (n,X) def iteration_newton(x0,m,epsilon,f,fp): def maj_test(xn,xnm1): return f(xn) != 0 and abs(xnm1-xn) > epsilon n=0; test= f(x0) != 0 xn=x0 X=[x0] while n < m and test: qn=fp(xn) xnm1=xn xn= xn-f(xn)/qn X += [xn] n=n+1 test= maj_test(xn,xnm1) #f(x) !=0 and nepsilon return (n,X) def iteration_corde(a,b,x0,m,epsilon,f): def maj_test(xn,xnm1): return f(xn) != 0 and abs(xnm1-xn) > epsilon n=0; q=float(f(b)-f(a))/(b-a) test= f(x0) != 0 xn=x0 X=[x0] while n < m and test: xnm1=xn xn= xn-f(xn)/q X += [xn] n=n+1 test= maj_test(xn,xnm1) #f(x) !=0 and nepsilon return (n,X) """def iteration_newton(x0,m,epsilon,f,fp): n=0; delta=float(1)/fp(x0) test= f(x0) != 0 x=x0 X=[x0] while(test): xm1=x x= x-delta*f(x) delta=float(1)/fp(x) X += [x] n=n+1 test= not (f(x)==0 or n>=m or abs(x-xm1)<=epsilon) return (n,X) """ def iteration_lagrange(x0,x1,m,epsilon,f): n=0; delta=float(x1-x0)/(f(x1)-f(x0)) test= f(x0) != 0 x=x1 X=[x1] while(test): xm1=x x= x-delta*f(x) delta=float(x-xm1)/(f(x)-f(xm1)) X += [x] n=n+1 test= not (f(x)==0 or n>=m or abs(x-xm1)<=epsilon) return (n,X) def main(): print "TP 3.1 ............ dichotomie" print iteration_dichotomie(0,pi/2,200,0.00000001,f) print "TP 3.1 ............ corde" print iteration_corde(0,pi/2,0,200,0.00000001,f) print "TP 3.1 ............ newton" print iteration_newton(0,200,0.00000001,f,fp) print "TP 3.1 ............ lagrange" print iteration_lagrange(0,pi/2,200,0.00000001,f) if __name__ == '__main__': main()