Bissection#
L’algorithme de la bissection est une méthode numérique utilisée pour trouver les racines d’une fonction continue sur un intervalle donné. L’objectif est de déterminer un intervalle où la fonction change de signe, ce qui indique la présence d’une racine à l’intérieur de cet intervalle. Ensuite, l’algorithme divise cet intervalle en deux parties égales et évalue la fonction au point médian. En fonction du signe du résultat, l’algorithme choisit le sous-intervalle contenant la racine et répète le processus jusqu’à ce qu’une précision suffisante soit atteinte. Cette méthode est particulièrement utile pour les fonctions continues mais peut nécessiter un nombre important d’itérations pour atteindre la précision souhaitée.
Fonction#
1import math
2
3def bisection(function, start_interval, end_interval):
4 """
5 Finds where the function becomes 0 in [start_interval, end_interval] using the bisection method.
6
7 Args:
8 function: The function for which to find the root.
9 start_interval: The start of the interval.
10 end_interval: The end of the interval.
11
12 Returns:
13 The root of the function within the given interval.
14 """
15 start = start_interval
16 end = end_interval
17
18 if function(start_interval) == 0:
19 return start_interval
20 elif function(end_interval) == 0:
21 return end_interval
22 elif function(start_interval) * function(end_interval) > 0:
23 print("Couldn't find root in [start_interval, end_interval]")
24 return
25 else:
26 mid = (start + end) / 2
27 while abs(start - mid) > 10**-7:
28 if function(mid) == 0:
29 return mid
30 elif function(mid) * function(start) < 0:
31 end = mid
32 else:
33 start = mid
34 mid = (start + end) / 2
35 return mid
36
37def f(x):
38 """
39 The function f(x) = x^3 - 2x - 5.
40
41 Args:
42 x: The input value.
43
44 Returns:
45 The result of the function.
46 """
47 return math.pow(x, 3) - 2*x - 5
print(bisection(f, 1, 1000))
2.0945515197818168