## Wednesday, January 19, 2011

### Problem 2 - the even Fibonacci Numbers

Problem 2:
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

I solved this using a basic recursive function - it's a fairly brute-force solution.
`~f = {|a=1,b=2,e=2| var c = a+b; (c<4000000).if ({  //add any even term to e  e = e+(c%2==0).if({c},{0});  ~f.(b,c,e); }, {  e; }); };~f.();`

Here's the code for a sonification that generates a spooky little overture:
It uses the sine tone generator from Problem 1
`~f = {|a=1,b=2,e=0| var c = a+b; (c<4000000).if ({  //add any even term to e  e = e+ (c%2==0).if({c},{0});  e.log.postln;  (e>0).if ({   Routine {    var s1,s2;    //put the wait at the front - rhythms accumulate as a duration of silence before the note    c.log.wait;    s1 = Synth("sine");    s1.set(\freq,64 * e.log,\atk,0.01,\rel,64 - c.log,\amp,0.1,\gate,1);   }.play;  });    ~f.(b,c,e); }, {  e; }); };~f.();`

One thing that the sonification of this solution makes really apparent is how the ratio of adjacent members of the Fibonacci series approaches the same value. The function pre-generates all of the notes before they are played, each one waiting it s turn to play as determined by the value of c.log.wait in the beginning of the Routine. I usually like a lot of symmetry in my music, which means I usually do things in integers or ratios of integers yet in this sequence, the notes all sound at very regular intervals even though their start times are not based on an integer. The pitch is determined by logarithm of the value of the variable e, the running sum of even numbered terms of the sequence - which always increases every 3rd term.

For a relatively small number of pitches this generates a pretty rich sound - there's more for me to explore here.