0

So I'm trying to follow along with the SICP lectures in Python, and have constructed the simple blackbox model for a Newtonian method of finding the square root approximations.

The code itself seems to work fine, but my function keeps returning a None? In the tryfor function below, I've made it such that it both prints the approximation AND returns it, such that the parent function can return the approximation.

I know from the print function that my code can find the right answer. However, when I write print(NewtonSqrt(2)), a None is returned - my approximation has not been 'returned' Confused as to why this is happening.

def NewtonSqrt(x):

  def improve(guess):
    return (guess + (x/guess)) / 2

  def goodenough(guess):
    if abs(guess - (x/guess)) < 0.00001:
      return True

  def tryfor(guess):
    if goodenough(guess) == True:
      print(guess)
      return guess
    else:
      tryfor(improve(guess))

  return tryfor(1)

print(NewtonSqrt(2))
Anoni Moose
  • 35
  • 1
  • 4
  • I'm not well versed in python, but shouldn't it be return tryfor(improve(guess)) in the else clause? – hager Jun 19 '19 at 09:50
  • Oh I see. What an embarrassing mistake - I'd spent hours on trying to solve it as well. Thank you so much!!! – Anoni Moose Jun 19 '19 at 10:05
  • while it's possible to follow it in python I suggest you to follow it in mit-scheme because it's a very difficult textbook and unless you don't want to finish it in more than 3 years you should focus on what sussman and abelson say, not on how to convert the scheme features in python. – alinsoar Jun 19 '19 at 16:57

1 Answers1

0

The code has two problem apart of the possibilities of optimizations. The first one is that you should respect the variables types if you are using float. Use

return (guess + (x/guess)) / 2.

instead of

return (guess + (x/guess)) / 2

The second one is the recursivity. The function tryfor must end with return:

  def NewtonSqrt(x):

      def improve(guess):
        return (guess + (x/guess)) / 2.

      def goodenough(guess):
        if abs(guess - (x/guess)) < 0.00001:
          return True

      def tryfor(guess):
        if goodenough(guess) == True:
          #print(guess)
          return guess
        else:
          return tryfor(improve(guess))

      return tryfor(1)

print(NewtonSqrt(2))

Now the output is going to be different of None. I hope you find it useful!!

Jamil KR
  • 66
  • 4