Created
July 18, 2021 09:11
-
-
Save AnuragAnalog/e20feae9ee024ad74b261e9b55322dc2 to your computer and use it in GitHub Desktop.
Newton Raphson method Implementation in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3.6 | |
# This method is generally used to improve the result obtained by one of the | |
# previous methods. Let x0 be an approximate root of f(x) = 0 and let x1 = x0 + h be | |
# the correct root so that f(x1) = 0. | |
# Expanding f(x0 + h) by Taylor’s series, we get | |
# f(x0) + hf′(x0) + h2/2! f′′(x0) + ...... = 0 | |
# Since h is small, neglecting h2 and higher powers of h, we get | |
# f(x0) + hf′(x0) = 0 or h = – f(x0)/f'(x0) | |
# A better approximation than x0 is therefore given by x1, where | |
# x1 = x0 - f(x0)/f'(x0) | |
# Successive approximations are given by x2, x3, ....... , xn + 1, where | |
# x(n+1) = xn - f(xn)/f'(xn) (n = 0, 1, 2, 3, .......) | |
# Which is Newton-Raphson formula. | |
def f(x): | |
fx = 3*x**2-15*x+7 | |
return fx | |
def fd(x): | |
fdx = 6*x-15 | |
return fdx | |
def newton(guess): | |
i = 0 | |
while True: | |
root = guess - (f(guess)/fd(guess)) | |
print(f"Root after iteration {i+1} is {root}.") | |
tmp1 = round(guess, 9) | |
tmp2 = round(root, 9) | |
if tmp1 == tmp2: | |
return root | |
guess = root | |
i = i + 1 | |
guess = float(input("Enter the guess value: ")) | |
root = newton(guess) | |
print(f"The final root is {root}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment