The doc’s aim is writing a procedure for finding a method for finding a square root according to Heron of Alexandria.

1. algorithmic definition for finding square root



  • composed of 7 functions
  • _tryThis is a recursive one
  • begins at the bottom with calling the initial guess 1 with return _truncate(_tryThis(1))
def sqrt(x):
    def _average(x, y):
        return (x+y)/2

    def _square(x):
        return x*x

    def _abs(x):
        if x < 0:
            return -x
        elif x == 0:
            return 0
            return x

    def _improve(guess):
        return _average(guess, (x/guess))

    def _goodEnough(guess):
        return _abs(_square(guess) - x) < 0.001

    def _tryThis(guess):
        if _goodEnough(guess):
            return guess
            return _tryThis(_improve(guess))

    def _truncate(n, decimals=3):
        multiplier = 10 ** decimals
        return int(n * multiplier) / multiplier

    return _truncate(_tryThis(1))

3. recursion

  • this is a recursive definition that allows to go on until something is true
  • note the independence of recursion hre: you don’t need any other looping constructother than the ability to call the procedure

4. block structure

  • structure where procedures contain other procedures within themselves
  • it is a package of procedures hidden inside the sqrt box
  • users should not care what is within the black box

5. sources