Skip to content

Instantly share code, notes, and snippets.

@LemonPi
Created October 12, 2013 01:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LemonPi/6944431 to your computer and use it in GitHub Desktop.
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
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