Skip to content

Commit 3a0555b

Browse files
authored
Create NewtonRaphsonMethod.py
Newton-Raphson method is non bracketing iterative algorithm to find the nearest root of an equation from point 'a'. It's much faster because convergence to the real root is very much faster than any other methods.
1 parent 0a1b6ad commit 3a0555b

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Implementing Newton Raphson method in python
2+
# Author: Haseeb
3+
4+
from sympy import diff
5+
from decimal import Decimal
6+
from math import sin, cos, exp
7+
8+
def NewtonRaphson(func, a):
9+
''' Finds root from the point 'a' onwards by Newton-Raphson method '''
10+
while True:
11+
x = a
12+
c = Decimal(a) - ( Decimal(eval(func)) / Decimal(eval(str(diff(func)))) )
13+
14+
x = c
15+
a = c
16+
# This number dictates the accuracy of the answer
17+
if abs(eval(func)) < 10**-15:
18+
return c
19+
20+
21+
# Let's Execute
22+
if __name__ == '__main__':
23+
# Find root of trignometric fucntion
24+
# Find value of pi
25+
print ('sin(x) = 0', NewtonRaphson('sin(x)', 2))
26+
27+
# Find root of polynomial
28+
print ('x**2 - 5*x +2 = 0', NewtonRaphson('x**2 - 5*x +2', 0.4))
29+
30+
# Find Square Root of 5
31+
print ('x**2 - 5 = 0', NewtonRaphson('x**2 - 5', 0.1))
32+
33+
# Exponential Roots
34+
print ('exp(x) - 1 = 0', NewtonRaphson('exp(x) - 1', 0))
35+
36+
37+
38+

0 commit comments

Comments
 (0)