1

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)

1 Answer 1

2

You almost had it! You were just failing to "remember" your last guess, check it out:

 def fixed_point(f, guess, epsilon=10**(-8), n=10):
      itr=0
      print "Guess:", guess
      test=f(guess)
      if (abs(test-guess)<epsilon):
          return(test)


      while ((n>itr) and (abs(test-guess)>=epsilon)):
          itr+=1
          guess = test
          test = f(test)
          print "Guess:",guess

          if ((abs(test-guess))<epsilon):
              return(test)

      return(None)


  print fixed_point(lambda x:x**2, 1, n=5)
  print fixed_point(lambda x:x**2, 0.5, n=5)
  print fixed_point(lambda x:x**2, 0.5, n=4)
  print fixed_point(lambda x:x**2, 2, n=5)
Sign up to request clarification or add additional context in comments.

1 Comment

Heh, I was wrong. The code can be fixed, but the problem is still the approach :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.