Skip to content

Commit b55043a

Browse files
committed
Added Fixed Point Iteration Method in numerical_analysis
1 parent 52602ea commit b55043a

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
"""
2+
Fixed Point Iteration Method
3+
4+
This method is used to find an approximate solution to a given equation f(x) = 0.
5+
The function g(x) is derived from f(x) such that x = g(x).
6+
7+
Example:
8+
--------
9+
>>> def g(x):
10+
... return (x**2 + 2) / 3
11+
>>> fixed_point_iteration(g, 1.0)
12+
1.618033988749895
13+
"""
14+
15+
def fixed_point_iteration(g, x0, tol=1e-7, max_iter=1000):
16+
"""
17+
Perform Fixed Point Iteration to find the root of the equation x = g(x).
18+
19+
Parameters:
20+
-----------
21+
g : function
22+
The function g(x) derived from f(x) such that x = g(x).
23+
x0 : float
24+
Initial guess for the root.
25+
tol : float, optional
26+
Tolerance for the convergence of the method. Default is 1e-7.
27+
max_iter : int, optional
28+
Maximum number of iterations. Default is 1000.
29+
30+
Returns:
31+
--------
32+
float
33+
The approximate root of the equation x = g(x).
34+
35+
Raises:
36+
-------
37+
ValueError
38+
If the method does not converge within the maximum number of iterations.
39+
"""
40+
x = x0
41+
for i in range(max_iter):
42+
x_new = g(x)
43+
if abs(x_new - x) < tol:
44+
return x_new
45+
x = x_new
46+
raise ValueError("Fixed Point Iteration did not converge")
47+
48+
if __name__ == "__main__":
49+
def g(x):
50+
return (x**2 + 2) / 3
51+
52+
root = fixed_point_iteration(g, 1.0)
53+
print(f"The root is: {root}")

0 commit comments

Comments
 (0)