Created
October 12, 2013 01:10
-
-
Save LemonPi/6944431 to your computer and use it in GitHub Desktop.
Newton's method for finding nth root of number r to p decimal places correct
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
def newton(n, r, p = 0): | |
""" | |
(int(n), num(r), int(p)) -> float | |
Return the nth root of a positive number r displaying p correct decimals. | |
""" | |
x = 1 # start with guess = 1 | |
while True: | |
fx = x**n - r # function of this form solves all roots | |
fdx = n * x**(n - 1) | |
x_n = x - (fx / fdx) | |
if abs(x_n - x) < 10**(-p): # checks consecutive difference | |
return round(x_n, p + 1) # show 1 extra decimal for rounding error | |
x = x_n | |
if __name__ == '__main__': | |
n = int(input("Which root to take: ")) | |
r = float(input("Which number to root: ")) | |
p = input("Decimal correct to: ") | |
if not p.isdigit(): # check if valid p is entered | |
p = 0 | |
print(newton(n, r, int(p))) # p as str cast into int |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment