[Edu-sig] Crunchy Fibonaccis

kirby urner kirby.urner at gmail.com
Thu Jul 27 21:05:17 CEST 2006


We've many times visited the Fibonaccis on this list.

In the general case, we start with any two numbers (the seed pair) and
add them to get the next in series, and so on, always adding the most
recent two to get the next in line.

Obviously, the Python generator is perfect for this, as it remembers
state between invocations (we invoke with .next() -- the standard
method for iterators in general).

New with Python 2.5 comes the ability to use the pause at "yield" to
send in some new grist for the mill -- let's say a new (a,b) seed
pair.   Here's what that looks like:

>>> def fibolater(a,b):
	while True:
		t = (yield a)
		if t is not None:
			a,b = t
		a,b = b, a + b

		
>>> f = fibolater(0,1)
>>> f.next()
0
>>> f.next()
1
>>> f.next()
1
>>> f.next()
2
>>> f.next()
3
>>> f.next()
5
>>> f.send((12,13))
13
>>> f.next()
25
>>> f.next()
38
>>> f.next()
63

The punch line with the Phi-bonaccis is f.next()/f.next() -- and yes,
that's legal Python -- approaches 1/phi.

>>> from __future__ import division
>>> f.next()/f.next()
0.61771561771561767
>>> f.next()/f.next()
0.61798753339269819
>>> f.next()/f.next()
0.61802721088435375
>>> f.next()/f.next()
0.6180329998700792
>>> f.next()/f.next()
0.61803384447421961
>>> f.next()/f.next()
0.61803396770035635
>>> f.next()/f.next()
0.61803398567880852

Note:  phi = (1 + pow(5, 0.5))/2

Related reading: http://mathforum.org/kb/message.jspa?messageID=3867841
(re the NCLB Polynomial from my Pentagon Math).

Kirby


More information about the Edu-sig mailing list