Skip to content

Commit 0a9aad4

Browse files
committed
Remove eval from arithmetic_analysis/newton_raphson.py
1 parent fdb0635 commit 0a9aad4

File tree

1 file changed

+17
-18
lines changed

1 file changed

+17
-18
lines changed

arithmetic_analysis/newton_raphson.py

Lines changed: 17 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -5,42 +5,41 @@
55
from __future__ import annotations
66

77
from decimal import Decimal
8-
from math import * # noqa: F403
98

10-
from sympy import diff
9+
from sympy import diff, lambdify, symbols
1110

1211

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:
1613
"""Finds root from the point 'a' onwards by Newton-Raphson method
1714
>>> newton_raphson("sin(x)", 2)
1815
3.1415926536808043
19-
>>> newton_raphson("x**2 - 5*x +2", 0.4)
16+
>>> newton_raphson("x**2 - 5*x + 2", 0.4)
2017
0.4384471871911695
2118
>>> newton_raphson("x**2 - 5", 0.1)
2219
2.23606797749979
23-
>>> newton_raphson("log(x)- 1", 2)
20+
>>> newton_raphson("log(x) - 1", 2)
2421
2.718281828458938
2522
"""
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
2727
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)
3431

3532

36-
# Let's Execute
3733
if __name__ == "__main__":
38-
# Find root of trigonometric function
34+
import doctest
35+
36+
doctest.testmod()
37+
3938
# Find value of pi
4039
print(f"The root of sin(x) = 0 is {newton_raphson('sin(x)', 2)}")
4140
# Find root of polynomial
4241
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
4443
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
4645
print(f"The root of exp(x) - 1 = 0 is {newton_raphson('exp(x) - 1', 0)}")

0 commit comments

Comments
 (0)