Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Newton's method for the search of the root of f(x) = x*log(x)-N. solution in Clear category for Super Root by Phil15
from math import log, fabs
#I rewrite x**x=N with x*log(x)=log(N) so we search the root of f(x)=x*log(x)-log(N).
def super_root(N, x0=1):
"""
Newton's method for the search of the root of the function f.
"""
f = lambda x: x*log(x)-log(N)
f_prime = lambda x: 1+log(x)
x1 = x0 - f(x0)/f_prime(x0)
if fabs(x1**x1-N)<0.001:
return x1
else:
return super_root(N, x1)
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
def check_result(function, number):
result = function(number)
if not isinstance(result, (int, float)):
print("The result should be a float or an integer.")
return False
p = result ** result
if number - 0.001 < p < number + 0.001:
return True
return False
assert check_result(super_root, 4), "Square"
assert check_result(super_root, 9), "Cube"
assert check_result(super_root, 81), "Eighty one"
March 4, 2018
Comments: