From 3a0555bdd7d9cfb4cfcf165249bb95b67cab3877 Mon Sep 17 00:00:00 2001 From: Syed Haseeb Shah Date: Fri, 13 Apr 2018 20:25:47 +0500 Subject: [PATCH] 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. --- ArithmeticAnalysis/NewtonRaphsonMethod.py | 38 +++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 ArithmeticAnalysis/NewtonRaphsonMethod.py diff --git a/ArithmeticAnalysis/NewtonRaphsonMethod.py b/ArithmeticAnalysis/NewtonRaphsonMethod.py new file mode 100644 index 000000000..40501134e --- /dev/null +++ b/ArithmeticAnalysis/NewtonRaphsonMethod.py @@ -0,0 +1,38 @@ +# Implementing Newton Raphson method in python +# Author: Haseeb + +from sympy import diff +from decimal import Decimal +from math import sin, cos, exp + +def NewtonRaphson(func, a): + ''' Finds root from the point 'a' onwards by Newton-Raphson method ''' + while True: + x = a + c = Decimal(a) - ( Decimal(eval(func)) / Decimal(eval(str(diff(func)))) ) + + x = c + a = c + # This number dictates the accuracy of the answer + if abs(eval(func)) < 10**-15: + return c + + +# Let's Execute +if __name__ == '__main__': + # Find root of trignometric fucntion + # Find value of pi + print ('sin(x) = 0', NewtonRaphson('sin(x)', 2)) + + # Find root of polynomial + print ('x**2 - 5*x +2 = 0', NewtonRaphson('x**2 - 5*x +2', 0.4)) + + # Find Square Root of 5 + print ('x**2 - 5 = 0', NewtonRaphson('x**2 - 5', 0.1)) + + # Exponential Roots + print ('exp(x) - 1 = 0', NewtonRaphson('exp(x) - 1', 0)) + + + +