SICP 01 — What is Block Structure with Bits on Recursion (in Python)

usecase

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

1. algorithmic definition for finding the square root

2. CODE

  • composed of 7 functions
  • _tryThis is a recursive
  • 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
else:
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
else:
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 here: you don’t need any other looping construct other than the ability to call the procedure

4. block structure

  • the 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

Written by

today I learnt… | as a support eng of the wonderful Snowplow Analytics, expect everything around modern (postmodern?) business intelligence

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store