|
| 1 | +# Implementing Newton Raphson method in Python |
| 2 | +# Author: Syed Haseeb Shah (github.com/QuantumNovice) |
| 3 | +# The Newton-Raphson method (also known as Newton's method) is a way to |
| 4 | +# quickly find a good approximation for the root of a real-valued function |
| 5 | + |
| 6 | +from decimal import Decimal |
| 7 | +from math import * # noqa: F401, F403 |
| 8 | +from sympy import diff |
| 9 | + |
| 10 | + |
| 11 | +def newton_raphson(func: str, a: int, precision: int=10 ** -10) -> float: |
| 12 | + """ Finds root from the point 'a' onwards by Newton-Raphson method |
| 13 | + >>> newton_raphson("sin(x)", 2) |
| 14 | + 3.1415926536808043 |
| 15 | + >>> newton_raphson("x**2 - 5*x +2", 0.4) |
| 16 | + 0.4384471871911695 |
| 17 | + >>> newton_raphson("x**2 - 5", 0.1) |
| 18 | + 2.23606797749979 |
| 19 | + >>> newton_raphson("log(x)- 1", 2) |
| 20 | + 2.718281828458938 |
| 21 | + """ |
| 22 | + x = a |
| 23 | + while True: |
| 24 | + x = Decimal(x) - (Decimal(eval(func)) / Decimal(eval(str(diff(func))))) |
| 25 | + # This number dictates the accuracy of the answer |
| 26 | + if abs(eval(func)) < precision: |
| 27 | + return float(x) |
| 28 | + |
| 29 | + |
| 30 | +# Let's Execute |
| 31 | +if __name__ == "__main__": |
| 32 | + # Find root of trigonometric function |
| 33 | + # Find value of pi |
| 34 | + print(f"The root of sin(x) = 0 is {newton_raphson('sin(x)', 2)}") |
| 35 | + # Find root of polynomial |
| 36 | + print(f"The root of x**2 - 5*x + 2 = 0 is {newton_raphson('x**2 - 5*x + 2', 0.4)}") |
| 37 | + # Find Square Root of 5 |
| 38 | + print(f"The root of log(x) - 1 = 0 is {newton_raphson('log(x) - 1', 2)}") |
| 39 | + # Exponential Roots |
| 40 | + print(f"The root of exp(x) - 1 = 0 is {newton_raphson('exp(x) - 1', 0)}") |
0 commit comments