Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Bisection 2 & newton's method solution in Clear category for Super Root by sodium
# migrated from python 2.7
import math
def newton(n):
# find solution with Newton's method
# f(x) = x**x - n
# f'(x) = (x**x)(ln(x)+1)
# x = x - f(x)/f'(x) = x - (x**x - n)/((x**x)(ln(x)+1))
x = 5.0
c = 0
while abs(x**x-n) >= 0.001:
x = x - (x**x - n)/((x**x)*math.log(x)+1)
c+=1
print(c)
return x
def bisection(n):
# find solution with bisection
a, b = 0.0, 10.0
c = 0
while True:
c+=1
x = (a+b)/2.0
if abs(x**x-n) < 0.001: break
if x**x < n: a, b = x, b
else: a, b = a, x
print(c)
return x
def super_root(n):
# f(x) = x**x - n
# solve x**x - n = 0
# as f(x) is very steep, newton's method is not effective.
return bisection(n)
#return newton(n)
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"
July 8, 2014