File tree 1 file changed +38
-0
lines changed
1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
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
+
You can’t perform that action at this time.
0 commit comments