Skip to content

Instantly share code, notes, and snippets.

@enigmaticape
Created November 4, 2012 15:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save enigmaticape/4012218 to your computer and use it in GitHub Desktop.
Save enigmaticape/4012218 to your computer and use it in GitHub Desktop.
Various python code to do Fibonacci related computations
#!/usr/bin/python
# This is the python script I used to generate
# the table that illustrates my rambling answer
# to SICP exercise 1.13
import math
# Golden ratio and conjugate
phi = (1 + math.sqrt( 5 ) ) / 2
psi = (1 - math.sqrt( 5 ) ) / 2
# Linear recursive fib
def fib( n ):
if n == 0 : return 0
if n == 1 : return 1
return fib( n - 1 ) + fib( n - 2 )
# approximation by golden ration
def goldfib( n ):
return ( phi**n ) / math.sqrt( 5 )
# approximation of diff by psi
def psiroot( n ):
return abs( ( psi**n ) / math.sqrt( 5 ) )
# closed form fib
def closed( n ):
return ( (phi**n - psi**n) / math.sqrt( 5 ))
# chuck out an HTML table
def drawtable():
n = 0
while n < 20:
print "<tr><td>\(",n,"\)</td>", \
"<td>\(",fib(n),"\)</td>", \
"<td>\(",goldfib(n),"\)</td>", \
"<td>\(",closed(n),"\)</td>", \
"<td>\(",psiroot(n),"\)</td></tr>"
n = n + 1
drawtable();
@enigmaticape
Copy link
Author

Used to generate the table of results that supports the solution to SICP exercise 1.13 at http://www.enigmaticape.com/blog/sicp-exercise-1-13/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment