Skip to content

Commit f4779bc

Browse files
rohitjoshi21cclauss
authored andcommitted
Bug Fixed in newton_raphson_method.py (TheAlgorithms#1634)
* Bug Fixed * Fixed newton_raphson_method.py * Fixed newton_raphson_method.py 2 * Fixed newton_raphson_method.py 3 * Fixed newton_raphson_method.py 4 * Fixed newton_raphson_method.py 5 * Fixed newton_raphson_method.py 6 * Update newton_raphson_method.py * Update newton_raphson_method.py * # noqa: F401, F403 * newton_raphson * newton_raphson * precision: int=10 ** -10 * return float(x) * 3.1415926536808043 * Update newton_raphson_method.py * 2.23606797749979 * Update newton_raphson_method.py * Rename newton_raphson_method.py to newton_raphson.py
1 parent bc5b92f commit f4779bc

File tree

2 files changed

+40
-34
lines changed

2 files changed

+40
-34
lines changed

arithmetic_analysis/newton_raphson.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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)}")

arithmetic_analysis/newton_raphson_method.py

Lines changed: 0 additions & 34 deletions
This file was deleted.

0 commit comments

Comments
 (0)