Newton's Method for nth root, as an integer arithmetic for Computers
The actual values of my previous post are truly astronomical, and when I reviewed my python3 implementation, I found I re-invented the wheel differently on paper. Here is my python3 code, with comments: It is slightly more conservative with actual values.
By experiment, it gives very good square roots for 3 - 8, at 4 iterations
############## main program ###############################
#
# This script attempts to calculate the nth root of k
#
#########################################################
k = int(input("Enter the number we are taking the root of: "))
n = int(input("Enter the power of the root: "))
i = int(input("How many iterations would you like to try? "))
a = k
b = n
#########################################################
#
# The formula for the Convergence Method is: x_k+1 = x_k - {[x_k^n]- K
# n[x_k]^n-1}
# This is also represented as
#
# [n-1/n (x_k)]+ [K/n * (1/x_k^n-1)]
#
# Doing algebra and representing x_k as a/b, I got:
#
# n-1 a + K b^n-1
# ----- * --- --- * -------
# n b n a^n-1
#
# Simplifying, this works out to:
#
# (n-1) * (a) (a)^n-1 + K * b * b^n-1
# ---------------------------------------
# n * b * a^n-1
#
# multiplying the a's and the b's, this results in three terms:
#
# (n-1) * (a)^n + K * (b)^n
# ------------------------------ (be careful not to square the n in the denominator)
# n * b * a^n-1
#
# Now I was able to recursively iterate with integer values. Compute each value
# first, before iterating, or a will influence b adversely
#
count = 0
while(count<i):
x = ((n-1)*(a**n))+(k*(b**n))
y = (n*b)*(a**(n-1))
a = x
b = y
# The math.gcd(a,b) function computes the largest number that divides both a and b
# If there is are common factors, gcd(a,b) figures out their product
x = math.gcd(a,b)
if(x!=0):
a = a // x
b = b // x
# Divide both a and b by greatest common denominator
count+=1
print()
Comments
Post a Comment