Fiche 18 - Algorithmique et Python
Fiche 18 - Algorithmique et Python
5 x Exercices 23
7 ¦ Corrigés détaillés 27
û º
Simulation Suites récurrentes Recherche
Loi des grands nbres Termes, seuils Seuil, extremum
3
Bases Python
Variables, boucles
L’idée directrice :
Chaque algorithme répond à une question précise du cours de maths. L’algorith-
mique n’est pas un chapitre isolé : c’est un outil transversal qui donne vie à
tous les autres chapitres. Un algorithme bien compris, c’est un théorème concret.
Python est un langage de programmation : une façon de donner des instructions à un ordinateur.
On écrit du texte (le code), l’ordinateur l’exécute ligne par ligne, de haut en bas. C’est comme
une recette de cuisine : chaque ligne est une étape.
Où écrire du Python ? Au lycée, on utilise généralement Thonny, Spyder, EduPython ou le site
[Link]. Tu écris dans l’éditeur (zone blanche) et tu cliques sur « Exécuter » (ou F5).
[ Définition | Variable
Une variable est une boîte dans la mémoire de l’ordinateur. Elle a un nom (l’étiquette) et contient
une valeur. Le symbole = signifie « mettre la valeur dans la boîte » (on dit affecter).
1 x = 5 # la bo î te x contient 5
2 nom = " Alice " # la bo î te nom contient le texte " Alice "
3 pi = 3.14159 # la bo î te pi contient 3.14159
4
5 x = x + 3 # on prend la valeur de x (5) , on ajoute 3 ,
6 # et on remet le r é sultat (8) dans x
7 print ( x ) # affiche 8
a + b Addition 7 + 3 10
a - b Soustraction 7 - 3 4
a * b Multiplication 7 * 3 21
a / b Division réelle 7 / 2 3.5
a // b Division entière 7 // 2 3
a % b Reste (modulo) 7 % 2 1
a ** b Puissance ab 2 ** 10 1024
1 x = 42
2 print ( x ) # affiche : 42
3 print ( " La valeur est " , x ) # affiche : La valeur est 42
4 print ( f " x vaut { x } " ) # affiche : x vaut 42 (f - string )
5 print ( f " x = { x **2} " ) # affiche : x = 1764
print affiche un résultat à l’écran. C’est différent de return (qui renvoie une valeur depuis une
fonction). Au bac, on te demande souvent « qu’affiche ce programme ? » — il faut repérer les
print.
== Égal à 5 == 5 True
!= Différent de 5 != 3 True
< Strictement inférieur 3 < 5 True
<= Inférieur ou égal 5 <= 5 True
> Strictement supérieur 3 > 5 False
>= Supérieur ou égal 7 >= 3 True
On peut combiner avec and (et), or (ou), not (non) :
(x > 0) and (x < 10) est vrai si 0 < x < 10.
La structure if permet d’exécuter certaines lignes seulement si une condition est vraie.
condition vraie ?
True False
suite du programme
1 note = 14
2
3 if note >= 16:
4 print ( " Tr è s bien " ) # ex é cut é si note >= 16
5 elif note >= 12:
6 print ( " Bien " ) # ex é cut é si 12 <= note < 16
7 elif note >= 10:
8 print ( " Passable " ) # ex é cut é si 10 <= note < 12
9 else :
10 print ( " Insuffisant " ) # ex é cut é si note < 10
11
12 # Ici , affiche " Bien " car 14 >= 12 et 14 < 16
Le code à l’intérieur d’un if doit être décalé de 4 espaces (ou 1 tabulation). C’est l’indentation.
Sans elle, Python ne sait pas quel code appartient au if.
1 # CORRECT :
2 if x > 0:
3 print ( " positif " ) # indent é = appartient au if
4
5 # ERREUR :
6 if x > 0:
7 print ( " positif " ) # pas indent é = erreur !
Règle simple : après chaque ligne qui finit par : (deux-points), on indente le bloc suivant.
La boucle for répète un bloc de code un nombre fixé de fois. La variable de boucle prend succes-
sivement chaque valeur d’une séquence.
1 # Affiche 0 , 1 , 2 , 3 , 4 (5 valeurs , de 0 à 4)
2 for i in range (5) :
3 print ( i )
4
5 # Affiche 1 , 2 , 3 , 4 , 5 ( de 1 à 5)
6 for i in range (1 , 6) : # ATTENTION : 6 est exclu !
7 print ( i )
8
9 # Affiche 0 , 2 , 4 , 6 , 8 ( de 0 à 8 , de 2 en 2)
10 for i in range (0 , 10 , 2) :
11 print ( i )
range(n) 0, 1, 2, . . . , n − 1 n valeurs
Pn 2
Exemple | Motif classique : calculer une somme k=1 k
Comprendre le mécanisme :
Tour k S (après)
1 1 0+1=1
2 2 1+4=5
3 3 5 + 9 = 14
4 4 14 + 16 = 30
.. .. ..
. . .
100 100 328350 + 10000 = 338350
3 for k in range (1 , n + 1) :
4 S = S + terme ( k ) # ou S += terme ( k )
5
6 # PRODUIT : P = a_1 a_2 ... a_n
7 P = 1 # neutre de la multiplication
8 for k in range (1 , n + 1) :
9 P = P * terme ( k ) # ou P *= terme ( k )
10
11 # COMPTEUR : combien de k v é rifient une condition ?
12 C = 0
13 for k in range (1 , n + 1) :
14 if condition ( k ) :
15 C = C + 1 # ou C += 1
La boucle while répète un bloc de code tant que la condition est vraie. On l’utilise quand on ne
sait pas à l’avance combien de répétitions seront nécessaires.
Comprendre le mécanisme :
Tour n 2n
– 0 1 ⩽ 1 000 000 → on continue
1 1 2 ⩽ 1 000 000 → on continue
2 2 4 ⩽ 1 000 000 → on continue
.. .. ..
. . .
19 19 524 288 ⩽ 1 000 000 → on continue
20 20 1 048 576 > 1 000 000 → on sort !
for while
Tu sais combien de fois ? Tu ne sais pas quand
répéter (nombre fixé) t’arrêter (condition)
Pn
Exemples : , afficher Exemples : un > M (seuil), b −
k=1
n termes, n lancers de dé a < ε (dichotomie), |un − ℓ| < ε
Une fonction est un bloc de code réutilisable. On la définit une fois avec def, puis on l’appelle
autant de fois qu’on veut.
def = je définis la recette. Appel = je lance la recette.
1 def f ( x ) :
2 return x + 1 # RENVOIE la valeur ( on peut la r é utiliser )
3
4 def g ( x ) :
5 print ( x + 1) # AFFICHE la valeur ( on ne peut pas la r é
utiliser )
6
7 a = f (5) # a vaut 6 ( la valeur est stock é e dans a )
8 b = g (5) # affiche 6 , mais b vaut None ( rien n ’ est renvoy é !)
6 def g ( x ) :
7 return math . exp ( x ) - 2* x # g(x) = e^x - 2x
8
9 def h ( x ) :
10 return math . log ( x ) + math . sqrt ( x ) # h ( x ) = ln ( x ) + x
11
12 def derive_approx (f , x , h =1 e -6) :
13 return ( f ( x + h ) - f ( x ) ) / h # f ’( x ) [f(x+h) - f(x)] / h
14
15 # Appels :
16 print ( f (2) ) # 4 - 6 + 1 = -1
17 print ( g (0) ) # 1 - 0 = 1
18 print ( h (1) ) # 0 + 1 = 1
[ Définition | Liste
Une liste est une variable qui contient plusieurs valeurs, numérotées à partir de 0. On la crée avec
des crochets [ ].
1 # Cr é er une liste
2 L = [10 , 20 , 30 , 40 , 50]
3
4 # Lire un é l é ment ( ATTENTION : on compte à partir de 0 !)
5 print ( L [0]) # 10 ( premier é l é ment )
13 # Modifier un é l é ment
14 L [1] = 99 # L = [10 , 99 , 30 , 40 , 50 , 60]
Indice 0 1 2 3 4
Valeur 10 20 30 40 50
L[5] provoque une erreur (il n’y a que 5 éléments, d’indices 0 à 4).
1 import random
2
3 # Nombre d é cimal al é atoire entre 0 ( inclus ) et 1 ( exclu )
4 x = random . random () # ex : 0.7234...
5
6 # Entier al é atoire entre a et b ( les deux inclus )
7 d = random . randint (1 , 6) # simule un d é : 1 , 2 , 3 , 4 , 5 ou 6
8
9 # Choisir un é l é ment au hasard dans une liste
10 couleur = random . choice ([ " rouge " , " bleu " , " vert " ])
1 import random
2
3 def pile_ou_face () :
4 if random . random () < 0.5: # 50% de chance
5 return " Pile "
6 else :
7 return " Face "
8
9 # Ou plus simplement : simuler un Bernoulli de param è tre p
10 def bernoulli ( p ) :
11 if random . random () < p:
12 return 1 # succ è s
13 else :
14 return 0 # é chec
Structure Modèle
Affectation x = valeur
Si f est continue sur [a, b] et f (a) · f (b) < 0, alors f s’annule au moins une fois sur ]a, b[.
On cherche un zéro de f sur [a, b]. L’idée : couper l’intervalle en deux à chaque étape.
1. Calculer m = a+b
2 (milieu).
2. Si f (a) · f (m) ⩽ 0 : le zéro est dans [a, m], poser b = m.
3. Sinon : le zéro est dans [m, b], poser a = m.
4. Répéter jusqu’à b − a < ε (précision voulue).
Après n étapes, l’intervalle a une largeur b−a
2n .
√
Exemple | Résoudre x 2 = 2 (⇔ trouver 2)
1 def f ( x ) :
2 return x **2 - 2
3
¥ Propriété | Complexité
b0 −a0
b0 −a0 ln
Après n étapes, la précision est 2n .Pour atteindre une précision ε : n ⩾ ε
ln 2 . C’est une
complexité logarithmique : très rapide.
yk+1 = yk + h · f (tk , yk )
1 def euler (f , t0 , y0 , h , n ) :
2 " " " M é thode d ’ Euler : n pas de taille h . " " "
3 T = [ t0 ]
4 Y = [ y0 ]
5 t , y = t0 , y0
6 for k in range ( n ) :
7 y = y + h * f (t , y )
8 t = t + h
9 T . append ( t )
10 Y . append ( y )
11 return T , Y
1 def f (t , y ) :
2 return -2 * y + 6
3
4 T , Y = euler (f , 0 , 1 , 0.01 , 500) # t de 0 à 5
5 # Y [ -1] 3.0000 ( converge vers y_infini = 3)
Plus h est petit, plus l’approximation est précise, mais plus le calcul est long. Un bon compromis
au bac : h = 0,01 ou h = 0,001. L’erreur d’Euler est proportionnelle à h (méthode d’ordre 1).
1 def riemann_gauche (f , a , b , n ) :
2 h = (b - a) / n
3 return h * sum ( f ( a + k * h ) for k in range ( n ) )
4
5 def riemann_droite (f , a , b , n ) :
6 h = (b - a) / n
7 return h * sum ( f ( a + k * h ) for k in range (1 , n + 1) )
8
9 def riemann_milieux (f , a , b , n ) :
10 h = (b - a) / n
11 return h * sum ( f ( a + ( k + 0.5) * h ) for k in range ( n ) )
1 import math
2 def f ( x ) :
3 return math . exp ( - x **2)
4
5 print ( riemann_milieux (f , 0 , 1 , 10000) ) # 0.74682
6 # Valeur exacte : /2 erf (1) 0.74682...
C’est l’intérêt majeur de Riemann : calculer des intégrales dont on ne connaît pas de primitive.
¥ Propriété | Précision
L’erreur des sommes à gauche/droite est en O n1 . L’erreur de la méthode des milieux est en O n12 :
1 import random
2
3 # Pile ou Face ( Bernoulli de param è tre 0.5)
4 def bernoulli ( p ) :
5 return 1 if random . random () < p else 0
1 import random
2 import matplotlib . pyplot as plt
3
4 def lo i_ gra nd s_ no mb re s (p , n ) :
5 " " " Trace la convergence de la fr é quence vers p . " " "
6 X = []
7 S = 0
8 for k in range (1 , n + 1) :
9 S += bernoulli ( p )
10 X . append ( S / k )
11 plt . plot (X , linewidth =0.8)
12 plt . axhline ( y =p , color = ’ red ’ , linestyle = ’ -- ’)
13 plt . xlabel ( ’n ’)
14 plt . ylabel ( ’ Fr é quence ’)
15 plt . title ( ’ Loi des grands nombres ’)
16 plt . show ()
17
18 loi _g ra nd s_ no mb re s (0.3 , 10000)
1 def binomiale (n , p ) :
2 " " " Simule X ~ B (n , p ) . " " "
3 return sum ( bernoulli ( p ) for _ in range ( n ) )
4
5 # Histogramme de 10000 simulations de B (20 , 0.3)
6 echantillon = [ binomiale (20 , 0.3) for _ in range (10000) ]
7 plt . hist ( echantillon , bins = range (22) , density = True ,
8 edgecolor = ’ black ’ , alpha =0.7)
9 plt . title ( ’ Histogramme B (20 , 0.3) ’)
10 plt . show ()
1 def termes_suite (f , u0 , n ) :
2 " " " Retourne la liste [ u_0 , u_1 , ... , u_n ]. " " "
3 U = [ u0 ]
4 u = u0
5 for k in range ( n ) :
6 u = f(u)
7 U . append ( u )
8 return U
9
10 # Exemple : u_ { n +1} = (2 + u_n ) , u_0 = 0
11 import math
12 U = termes_suite ( lambda u : math . sqrt (2 + u ) , 0 , 20)
13 print ( U [ -1]) # 2.0 ( la suite converge vers 2)
1 def seuil (f , u0 , M ) :
2 " " " Retourne le plus petit n tel que u_n > M . " " "
3 u = u0
4 n = 0
5 while u <= M :
6 u = f(u)
7 n += 1
8 return n
9
10 # Exemple : u_ { n +1} = 1.05 * u_n ( croissance 5%) , u_0 = 100
11 # Combien d ’ ann é es pour d é passer 200 ?
12 n = seuil ( lambda u : 1.05 * u , 100 , 200)
13 print ( n ) # 15 ( il faut 15 ans pour doubler )
Si la suite ne dépasse jamais M (par exemple suite décroissante), la boucle while ne s’arrête jamais.
En pratique, on ajoute un compteur de sécurité :
1 def seuil_securise (f , u0 , M , max_iter =100000) :
2 u , n = u0 , 0
3 while u <= M and n < max_iter :
4 u = f(u)
5 n += 1
6 return n if u > M else None
1 def pascal ( n ) :
2 " " " Retourne le triangle de Pascal jusqu ’à la ligne n . " " "
3 T = [[1]]
4 for k in range (1 , n + 1) :
5 ligne = [1]
6 for j in range (1 , k ) :
7 ligne . append ( T [k -1][ j -1] + T [k -1][ j ])
8 ligne . append (1)
9 T . append ( ligne )
10 return T
11
12 # Coefficients binomiaux C (10 , k )
13 T = pascal (10)
14 print ( T [10]) # [1 , 10 , 45 , 120 , 210 , 252 , 210 , 120 , 45 , 10 , 1]
1 import math
2
3 def binom (n , k ) :
4 " " " C (n , k ) = n ! / ( k ! * (n - k ) !) " " "
5 return math . factorial ( n ) // ( math . factorial ( k ) * math . factorial ( n
- k))
6
1 import numpy as np
2 import matplotlib . pyplot as plt
3
4 x = np . linspace ( -2 , 4 , 1000)
5 y = x **2 - 3* x + 1
6
7 plt . figure ( figsize =(8 , 5) )
8 plt . plot (x , y , color = ’ steelblue ’ , linewidth =2 , label = r ’ $f ( x ) = x ^2 -3 x +1 $
’)
9 plt . axhline (0 , color = ’ black ’ , linewidth =0.5)
10 plt . axvline (0 , color = ’ black ’ , linewidth =0.5)
11 plt . grid ( alpha =0.3)
12 plt . legend ( fontsize =12)
13 plt . xlabel ( ’x ’)
14 plt . ylabel ( ’f ( x ) ’)
15 plt . title ( ’ Graphe de f ’)
16 plt . show ()
1 import numpy as np
2 import matplotlib . pyplot as plt
3
4 def euler_plot (f , t0 , y0 , h , n ) :
5 T , Y = euler (f , t0 , y0 , h , n )
6 plt . plot (T , Y , ’o - ’ , markersize =2 , label = f ’ Euler ( h ={ h }) ’)
7
8 # y ’ = -2 y + 6 , y (0) = 1
9 f = lambda t , y: -2* y + 6
10 euler_plot (f , 0, 1 , 0.5 , 10) # pas grossier
11 euler_plot (f , 0, 1 , 0.1 , 50) # pas moyen
12 euler_plot (f , 0, 1 , 0.01 , 500) # pas fin
13
14 # Solution exacte
15 t = np . linspace (0 , 5 , 200)
16 plt . plot (t , -2* np . exp ( -2* t ) + 3 , ’r - - ’ , linewidth =2 , label = ’ Exacte ’)
17 plt . legend ()
18 plt . title ( " M é thode d ’ Euler : effet du pas h " )
19 plt . show ()
Fréquence,
Simulation Probabilités, LGN
estimation
n
k Triangle de Pascal Dénombrement
1. Lire un algorithme = exécuter à la main. Faire un tableau de valeurs des variables étape
par étape.
2. for = nombre d’itérations connu, while = condition d’arrêt.
3. range(n) = 0, 1, . . . , n − 1 (n termes). range(1,n+1) = 1, . . . , n.
4. Initialiser les variables avant la boucle. Oublier l’initialisation est l’erreur #1.
5. Accumulateur : S = 0 puis S += terme dans la boucle (pour sommer).
6. Dichotomie : vérifier f (a) · f (b) < 0 avant de lancer. Sinon, pas de zéro garanti.
7. Euler : un petit pas h donne une meilleure approximation mais plus de calculs.
8. Simulation : toujours faire beaucoup de répétitions (n ⩾ 1000) pour la LGN.
9. Indentation = structure. Un décalage en trop ou en moins change tout le programme.
10. Tester son code avec des cas simples dont on connaît la réponse.
Pour comprendre ce que fait un algorithme, on trace un tableau d’évolution des variables :
Étape k S u condition
Init – 0 1 –
k=0 0 1 2 –
k=1 1 3 4 –
k=2 2 7 8 –
..
.
C’est la méthode la plus sûre pour répondre aux questions « que vaut S après la boucle ? ».
5 x Exercices
Exercice 1 ⋆ ⋆ ⋆ — Lire un algorithme
Que retourne la fonction suivante pour n = 5 ?
1 def mystere ( n ) :
2 S = 0
3 for k in range (1 , n + 1) :
4 S = S + k **2
5 return S
Exercice 4 ⋆ ⋆ ⋆ — Dichotomie
a) Utiliser la dichotomie pour résoudre ex = 3x sur [1, 2] à 10−8 près.
b) Combien d’étapes sont nécessaires ?
√
c) Adapter pour trouver 3 7 (zéro de x 3 − 7 sur [1, 2]).
c) Estimer 01 1+x
1 dx et vérifier que c’est ≈ π .
R
2 4
La méthode de Newton est une alternative à la dichotomie pour trouver les zéros d’une fonction.
Elle est beaucoup plus rapide mais nécessite de connaître la dérivée.
f (xn )
xn+1 = xn − ′
f (xn )
Partie B — Programmation
4. Écrire une fonction Python newton(f, df, x0, eps, max_iter) qui implémente la méthode de
Newton.
5. Appliquer à f (x ) = x 2 − 2 (donc f ′ (x ) = 2x ) avec x0 = 1. Combien d’itérations pour atteindre
10−15 ?
6. Comparer avec la dichotomie : combien d’itérations faut-il en dichotomie pour la même précision ?
Partie C — Convergence
7. On note en = xn − α l’erreur à l’étape n. En utilisant un développement de Taylor de f autour de α,
montrer que :
f ′′ (α) 2
en+1 ≈ ′ ·e
2f (α) n
8. Que signifie en+1 ≈ C · en2 ? Expliquer pourquoi Newton est quadratiquement convergente : le
nombre de décimales correctes double à chaque étape.
√
9. Pour f (x ) = x 2 − 2 et x0 = 1, calculer x1 , x2 , x3 , x4 et compter les décimales correctes de 2.
7 ¦ Corrigés détaillés
Exercice 1
On trace le tableau d’exécution pour n = 5 :
k k2 S
– – 0
1 1 1
2 4 5
3 9 14
4 16 30
5 25 55
La fonction retourne S = 12 + 22 + 32 + 42 + 52 = 55 .
Pn n(n+1)(2n+1)
En général, mystere(n) retourne k=1 k
2 = 6 .
Exercice 2
1 def factorielle ( n ) :
2 F = 1
3 for k in range (1 , n + 1) :
4 F = F * k
5 return F
Exercice 3
a) et b) :
1 u = 1
2 for n in range (20) :
3 print ( f " u_ { n } = { u :.10 f } " )
4 u = ( u + 3) / 2
n
Il faut n = 21 étapes. En effet, un − 3 = −2 · 12 , donc |un − 3| < 10−6 ⇐⇒ 2 · 2−n < 10−6 ⇐⇒ n >
ln(2×106 )
ln 2 ≈ 20,9.
Exercice 4
a) On cherche le zéro de f (x ) = ex − 3x sur [1, 2].
f (1) = e − 3 ≈ −0,282 < 0 et f (2) = e2 − 6 ≈ 1,389 > 0.
1 import math
2 def f ( x ) :
3 return math . exp ( x ) - 3* x
4
5 resultat = dichotomie (f , 1 , 2 , 1e -8)
6 print ( resultat ) # 1.51213455
ln(1/10−8 )
b) Nombre d’étapes : n ⩾ ln 2 = 8 ln
ln 10 ≈ 26,6, donc 27 étapes.
2
c) Zéro de g(x ) = x 3 − 7 sur [1, 2] : g(1) = −6 < 0, g(2) = 1 > 0.
1 resultat = dichotomie ( lambda x : x **3 - 7 , 1 , 2 , 1e -8)
2 print ( resultat ) # 1.91293118
Exercice 5
a) y ′ = y , y (0) = 1, solution exacte y (t) = et .
Euler avec h = 0,1 : yk+1 = yk + 0,1 · yk = 1,1 · yk . Donc yk = 1,1k .
y10 = 1,110 ≈ 2,5937. Valeur exacte : e ≈ 2,7183. Erreur ≈ 4,6%.
b) Avec h = 0,01 : y100 = 1,01100 ≈ 2,7048. Erreur ≈ 0,5%. Oui, bien meilleure.
c)
1 import math
2 T , Y = euler ( lambda t , y : -y + math . sin ( t ) , 0 , 0 , 0.01 , 1000)
3 plt . plot (T , Y )
4 plt . title ( " y ’ = -y + sin ( t ) " )
5 plt . show ()
Exercice 6
a) 01 x 3 dx = 14 = 0,25.
R
c) 01 1+x
1 dx = arctan(1) = π ≈ 0,7854. Vérifié.
R
2 4
Exercice 7
a)
1 import random
2 compteur = 0
3 N = 10000
4 for _ in range ( N ) :
5 d1 = random . randint (1 , 6)
6 d2 = random . randint (1 , 6)
7 if d1 + d2 == 7:
8 compteur += 1
b)
1 def a n n i v er s a i r e _ s i m u l a t i o n (n , N =10000) :
2 compteur = 0
3 for _ in range ( N ) :
4 dates = set ()
5 collision = False
6 for _ in range ( n ) :
7 d = random . randint (1 , 365)
8 if d in dates :
9 collision = True
10 break
11 dates . add ( d )
12 if collision :
13 compteur += 1
14 return compteur / N
15
16 print ( a n n iv e r s a i r e _ s i m u l a t i o n (23) ) # 0.507
c)
1 for _ in range (5) :
2 positions = [0]
3 x = 0
4 for _ in range (1000) :
5 x += random . choice ([ -1 , 1])
6 positions . append ( x )
7 plt . plot ( positions , linewidth =0.5)
8 plt . title ( " 5 marches al é atoires " )
9 plt . show ()
Exercice 8
a) f (x ) = ln(x ) − 2. L’algorithme cherche le zéro de f , c’est-à-dire la solution de ln(x ) = 2, soit x = e2 .
b) algo(0.001) retourne une valeur approchée de e2 ≈ 7,389, à 0,001 près.
Exercice 9
a) u0 = 1000 et un+1 = 1,03 · un . Donc un = 1000 × 1,03n .
b)
1 u = 1000
2 n = 0
3 while u <= 2000:
4 u = 1.03 * u
5 n += 1
6 print ( n ) # 24
Exercice 10
Tableau d’exécution :
S = 1 + 2 + 4 + 8 + 16 = 31 = 25 − 1.
Pn−1 k
En général, cet algorithme calcule k=0 2 = 2 − 1.
n
Exercice 11
a) y ′ = −0,5y +2 est de la forme y ′ = ay +b avec a = −0,5, b = 2. Solution générale : y (t) = C e−0,5t +4.
Avec y (0) = 10 : C = 6, donc y (t) = 6e−0,5t + 4.
b) Euler avec h = 0,5 :
y0 = 10.
y1 = 10 + 0,5 × (−0,5 × 10 + 2) = 10 + 0,5 × (−3) = 8,5.
y2 = 8,5 + 0,5 × (−0,5 × 8,5 + 2) = 8,5 + 0,5 × (−2,25) = 7,375.
y3 = 7,375 + 0,5 × (−0,5 × 7,375 + 2) = 7,375 + 0,5 × (−1,6875) = 6,531.
y4 = 6,531 + 0,5 × (−0,5 × 6,531 + 2) = 6,531 + 0,5 × (−1,266) = 5,898.
c) Comparaison :
t Euler (h = 0,5) Exacte Erreur
0,5 8,500 8,680 2,1%
1,0 7,375 7,639 3,5%
1,5 6,531 6,804 4,0%
2,0 5,898 6,207 5,0%
Exercice 12
a) Tchebychev : p ∈ fn − √ 1 ; fn + √ 1 .
20n 20n
La borne de Tchebychev est très pessimiste : l’intervalle est plus fiable que 95% en pratique (par le TCL,
c’est plutôt ≈ 99,8%).
Exercice 13
a) L’aire du quart de disque est π4 , l’aire du carré est 1. Un point aléatoire uniforme dans [0, 1]2 tombe
dans le quart de disque avec probabilité π4 . Par la LGN, la fréquence converge vers π4 .
b)
1 import random
2 def monte_carlo_pi ( n ) :
3 compteur = 0
4 for _ in range ( n ) :
5 x = random . random ()
6 y = random . random ()
7 if x **2 + y **2 <= 1:
8 compteur += 1
9 return 4 * compteur / n
10
Exercice 14
a) y (t) = 12 (sin t + cos t − e−t ).
y ′ (t) = 21 (cos t − sin t + e−t ).
cos t − y (t) = cos t − 12 sin t − 21 cos t + 12 e−t = 21 cos t − 12 sin t + 12 e−t = y ′ (t). ✓
y (0) = 21 (0 + 1 − 1) = 0. ✓
b)–c)
1 import math , numpy as np , matplotlib . pyplot as plt
2
3 for h in [0.1 , 0.01 , 0.001]:
4 n = int (10 / h )
5 T , Y = euler ( lambda t , y : math . cos ( t ) - y , 0 , 0 , h , n )
6 plt . plot (T , Y , label = f ’h ={ h } ’)
7
8 t = np . linspace (0 , 10 , 1000)
9 y_exact = 0.5 * ( np . sin ( t ) + np . cos ( t ) - np . exp ( - t ) )
10 plt . plot (t , y_exact , ’k - - ’ , linewidth =2 , label = ’ Exacte ’)
11 plt . legend ()
12 plt . show ()
d) Erreur maximale :
h Erreur max
0,1 ≈ 0,048
0,01 ≈ 0,0048
0,001 ≈ 0,00048
L’erreur est bien proportionnelle à h : diviser h par 10 divise l’erreur par 10. C’est la convergence d’ordre
1 d’Euler.
f (xn )
xn+1 = xn − ′
f (xn )
3. Géométriquement : on suit la tangente jusqu’à l’axe des abscisses. Si f est convexe et le point initial
bien choisi, les approximations convergent rapidement vers le zéro.
Partie B — Programmation
4.
1 def newton (f , df , x0 , eps , max_iter =100) :
2 x = x0
3 for i in range ( max_iter ) :
4 fx = f ( x )
5 if abs ( fx ) < eps :
6 return x , i
7 dfx = df ( x )
8 if dfx == 0:
9 return None , i # tangente horizontale
10 x = x - fx / dfx
11 return x , max_iter
5. f (x ) = x 2 − 2, f ′ (x ) = 2x , x0 = 1 :
1 resultat , nb = newton ( lambda x : x **2 - 2 , lambda x : 2* x , 1 , 1e -15)
2 print ( f " x = { resultat } , it é rations = { nb } " )
3 # x = 1.4142135623730951 , it é rations = 5
Partie C — Convergence
7. Taylor de f autour de α (f (α) = 0) :
f ′′ (α) 2 f ′′ (α) 2
f (xn ) = f (α) + f ′ (α)en + 2 en + · · · = f ′ (α)en + 2 en + ···
f ′ (xn ) = f ′ (α) + f ′′ (α)en + · · · ≈ f ′ (α) (au premier ordre).
f ′′ (α)
f (x ) f ′ (α)en + 2 en2
en+1 = xn+1 − α = xn − f ′ (xn ) − α = en − f ′ (α)+···
n
f ′′ (α) f ′′ (α)
≈ en − en − 2f ′ (α) en2 = 2f ′ (α) · en2 . □
8. en+1 ≈ C ·en2 signifie que l’erreur est mise au carré à chaque étape. Si en ≈ 10−k , alors en+1 ≈ C ·10−2k .
Le nombre de décimales correctes double à chaque itération :
1 → 2 → 4 → 8 → 16 décimales en 5 itérations.
9. Pour f (x ) = x 2 − 2, f ′ (x ) = 2x :
2 2
n −2 = xn +2 = 1 x + 2
xn+1 = xn − x2x
n 2xn 2 n xn
(C’est la méthode de Héron / babylonienne !)
x0 = 1. x1 = 12 (1 + 2) = 1,5. x2 = 12 (1,5 + 1,5
2 ) = 1 × 17 ≈ 1,416667.
2 6
x3 ≈ 1,414215686. x4 ≈ 1,414213562373095.
√
2 ≈ 1,414213562373099. Après 4 itérations : 13 décimales correctes.
La dichotomie garantit la convergence (robustesse), Newton accélère la précision (rapidité). C’est la stra-
tégie utilisée dans les logiciels professionnels.