1+ """
2+ Modified Newton-Raphson Method
3+
4+ This method is used to find an approximate solution to a given equation f(x) = 0.
5+ It is an iterative method that modifies the standard Newton-Raphson method to improve
6+ convergence in certain cases, mostly when multiplicity is more than 1.
7+
8+ Example:
9+ --------
10+ >>> import math
11+ >>> def f(x):
12+ ... return x**3 - 2*x - 5
13+ >>> def f_prime(x):
14+ ... return 3*x**2 - 2
15+ >>> modified_newton_raphson(f, f_prime, 2.0)
16+ 2.0945514815423265
17+ """
18+
19+ from typing import Callable
20+
21+ def modified_newton_raphson (
22+ f : Callable [[float ], float ],
23+ f_prime : Callable [[float ], float ],
24+ x0 : float ,
25+ tol : float = 1e-7 ,
26+ max_iter : int = 1000
27+ ) -> float :
28+ """
29+ Perform the Modified Newton-Raphson method to find the root of the equation f(x) = 0.
30+
31+ Parameters:
32+ -----------
33+ f : function
34+ The function for which we want to find the root.
35+ f_prime : function
36+ The derivative of the function f.
37+ x0 : float
38+ Initial guess for the root.
39+ tol : float, optional
40+ Tolerance for the convergence of the method. Default is 1e-7.
41+ max_iter : int, optional
42+ Maximum number of iterations. Default is 1000.
43+
44+ Returns:
45+ --------
46+ float
47+ The approximate root of the equation f(x) = 0.
48+
49+ Raises:
50+ -------
51+ ValueError
52+ If the method does not converge within the maximum number of iterations.
53+ """
54+ x = x0
55+ for i in range (max_iter ):
56+ fx = f (x )
57+ fpx = f_prime (x )
58+ if fpx == 0 :
59+ raise ValueError ("Derivative is zero. No solution found." )
60+ x_new = x - fx / fpx
61+ if abs (x_new - x ) < tol :
62+ return x_new
63+ x = x_new
64+ raise ValueError ("Modified Newton-Raphson method did not converge" )
65+
66+ if __name__ == "__main__" :
67+ import math
68+
69+ def f (x ):
70+ return x ** 3 - 2 * x - 5
71+
72+ def f_prime (x ):
73+ return 3 * x ** 2 - 2
74+
75+ root = modified_newton_raphson (f , f_prime , 2.0 )
76+ print (f"The root is: { root } " )
0 commit comments