A fixed point for a function is the point where f(x)=x.
For a specific function I'm supposed to find the fixed point by starting with a random guess and then calucalting f again and again, i.e.: calculating f(x), f(f(x)), f(f(f(x))),... until the value doesn't change over epsilon.
the function I'm supposed to write gets as an input: a function, a random guess, epsilon, and n the number of iterations. the function should calculate an approximation for a fixed point. It will stop when the difference between the two numbers is smaller than epsilon, or when n iterations have been done. input and output examples:
>>> fixed_point(lambda x:x**2, 1, n=5)
1 #0 iterations needed, initial guess suffices
>>> fixed_point(lambda x:x**2, 0.5, n=5)
5.421010862427522e-20 #after 5 iterations
>>> fixed_point(lambda x:x**2, 0.5, n=4)
>>> #returns None
>>> fixed_point(lambda x:x**2, 2, n=5)
>>> #returns None, guesses were: 2, 4, 16, 256, 65536, 4294967296
My code gives a correct answer only for the first example, What should I fix in it?
def fixed_point(f, guess, epsilon=10**(-8), n=10):
itr=0
test=f(guess)
if (abs(test-guess)<epsilon):
return(test)
while ((n>itr) and (abs(test-guess)>=epsilon)):
itr+=1
test=f(test)
if ((abs(test-guess))<epsilon):
return(test)
return(None)