Python/arithmetic_analysis/newton_raphson_method.py

35 lines
1.0 KiB
Python
Raw Normal View History

2018-10-19 12:48:28 +00:00
# Implementing Newton Raphson method in Python
# Author: Syed Haseeb Shah (github.com/QuantumNovice)
2019-10-05 05:14:13 +00:00
# The Newton-Raphson method (also known as Newton's method) is a way to
# quickly find a good approximation for the root of a real-valued function
2018-10-19 12:48:28 +00:00
from sympy import diff
from decimal import Decimal
2019-10-05 05:14:13 +00:00
2018-10-19 12:48:28 +00:00
def NewtonRaphson(func, a):
2019-10-05 05:14:13 +00:00
""" Finds root from the point 'a' onwards by Newton-Raphson method """
2018-10-19 12:48:28 +00:00
while True:
2019-10-05 05:14:13 +00:00
c = Decimal(a) - (Decimal(eval(func)) / Decimal(eval(str(diff(func)))))
2018-10-19 12:48:28 +00:00
a = c
# This number dictates the accuracy of the answer
2019-10-05 05:14:13 +00:00
if abs(eval(func)) < 10 ** -15:
return c
2018-10-19 12:48:28 +00:00
# Let's Execute
2019-10-05 05:14:13 +00:00
if __name__ == "__main__":
2018-10-19 12:48:28 +00:00
# Find root of trigonometric function
# Find value of pi
2019-10-05 05:14:13 +00:00
print("sin(x) = 0", NewtonRaphson("sin(x)", 2))
2018-10-19 12:48:28 +00:00
# Find root of polynomial
2019-10-05 05:14:13 +00:00
print("x**2 - 5*x +2 = 0", NewtonRaphson("x**2 - 5*x +2", 0.4))
2018-10-19 12:48:28 +00:00
# Find Square Root of 5
2019-10-05 05:14:13 +00:00
print("x**2 - 5 = 0", NewtonRaphson("x**2 - 5", 0.1))
2018-10-19 12:48:28 +00:00
# Exponential Roots
2019-10-05 05:14:13 +00:00
print("exp(x) - 1 = 0", NewtonRaphson("exp(x) - 1", 0))