|
| 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 | + |
| 22 | +def modified_newton_raphson( |
| 23 | + f: Callable[[float], float], |
| 24 | + f_prime: Callable[[float], float], |
| 25 | + x0: float, |
| 26 | + tol: float = 1e-7, |
| 27 | + max_iter: int = 1000, |
| 28 | +) -> float: |
| 29 | + """ |
| 30 | + Perform the Modified Newton-Raphson method to find the root of the equation f(x) = 0. |
| 31 | +
|
| 32 | + Parameters: |
| 33 | + ----------- |
| 34 | + f : function |
| 35 | + The function for which we want to find the root. |
| 36 | + f_prime : function |
| 37 | + The derivative of the function f. |
| 38 | + x0 : float |
| 39 | + Initial guess for the root. |
| 40 | + tol : float, optional |
| 41 | + Tolerance for the convergence of the method. Default is 1e-7. |
| 42 | + max_iter : int, optional |
| 43 | + Maximum number of iterations. Default is 1000. |
| 44 | +
|
| 45 | + Returns: |
| 46 | + -------- |
| 47 | + float |
| 48 | + The approximate root of the equation f(x) = 0. |
| 49 | +
|
| 50 | + Raises: |
| 51 | + ------- |
| 52 | + ValueError |
| 53 | + If the method does not converge within the maximum number of iterations. |
| 54 | + """ |
| 55 | + x = x0 |
| 56 | + for i in range(max_iter): |
| 57 | + fx = f(x) |
| 58 | + fpx = f_prime(x) |
| 59 | + if fpx == 0: |
| 60 | + raise ValueError("Derivative is zero. No solution found.") |
| 61 | + x_new = x - fx / fpx |
| 62 | + if abs(x_new - x) < tol: |
| 63 | + return x_new |
| 64 | + x = x_new |
| 65 | + raise ValueError("Modified Newton-Raphson method did not converge") |
| 66 | + |
| 67 | + |
| 68 | +if __name__ == "__main__": |
| 69 | + import math |
| 70 | + |
| 71 | + def f(x): |
| 72 | + return x**3 - 2 * x - 5 |
| 73 | + |
| 74 | + def f_prime(x): |
| 75 | + return 3 * x**2 - 2 |
| 76 | + |
| 77 | + root = modified_newton_raphson(f, f_prime, 2.0) |
| 78 | + print(f"The root is: {root}") |
0 commit comments