|
5 | 5 | from __future__ import annotations
|
6 | 6 |
|
7 | 7 | from decimal import Decimal
|
8 |
| -from math import * # noqa: F403 |
9 | 8 |
|
10 |
| -from sympy import diff |
| 9 | +from sympy import diff, lambdify, symbols |
11 | 10 |
|
12 | 11 |
|
13 |
| -def newton_raphson( |
14 |
| - func: str, a: float | Decimal, precision: float = 10**-10 |
15 |
| -) -> float: |
| 12 | +def newton_raphson(func: str, a: float | Decimal, precision: float = 1e-10) -> float: |
16 | 13 | """Finds root from the point 'a' onwards by Newton-Raphson method
|
17 | 14 | >>> newton_raphson("sin(x)", 2)
|
18 | 15 | 3.1415926536808043
|
19 |
| - >>> newton_raphson("x**2 - 5*x +2", 0.4) |
| 16 | + >>> newton_raphson("x**2 - 5*x + 2", 0.4) |
20 | 17 | 0.4384471871911695
|
21 | 18 | >>> newton_raphson("x**2 - 5", 0.1)
|
22 | 19 | 2.23606797749979
|
23 |
| - >>> newton_raphson("log(x)- 1", 2) |
| 20 | + >>> newton_raphson("log(x) - 1", 2) |
24 | 21 | 2.718281828458938
|
25 | 22 | """
|
26 |
| - x = a |
| 23 | + x = symbols("x") |
| 24 | + f = lambdify(x, func, "math") |
| 25 | + f_derivative = lambdify(x, diff(func), "math") |
| 26 | + x_curr = a |
27 | 27 | while True:
|
28 |
| - x = Decimal(x) - ( |
29 |
| - Decimal(eval(func)) / Decimal(eval(str(diff(func)))) # noqa: S307 |
30 |
| - ) |
31 |
| - # This number dictates the accuracy of the answer |
32 |
| - if abs(eval(func)) < precision: # noqa: S307 |
33 |
| - return float(x) |
| 28 | + x_curr = Decimal(x_curr) - Decimal(f(x_curr)) / Decimal(f_derivative(x_curr)) |
| 29 | + if abs(f(x_curr)) < precision: |
| 30 | + return float(x_curr) |
34 | 31 |
|
35 | 32 |
|
36 |
| -# Let's Execute |
37 | 33 | if __name__ == "__main__":
|
38 |
| - # Find root of trigonometric function |
| 34 | + import doctest |
| 35 | + |
| 36 | + doctest.testmod() |
| 37 | + |
39 | 38 | # Find value of pi
|
40 | 39 | print(f"The root of sin(x) = 0 is {newton_raphson('sin(x)', 2)}")
|
41 | 40 | # Find root of polynomial
|
42 | 41 | print(f"The root of x**2 - 5*x + 2 = 0 is {newton_raphson('x**2 - 5*x + 2', 0.4)}")
|
43 |
| - # Find Square Root of 5 |
| 42 | + # Find value of e |
44 | 43 | print(f"The root of log(x) - 1 = 0 is {newton_raphson('log(x) - 1', 2)}")
|
45 |
| - # Exponential Roots |
| 44 | + # Find root of exponential function |
46 | 45 | print(f"The root of exp(x) - 1 = 0 is {newton_raphson('exp(x) - 1', 0)}")
|
0 commit comments