## October 01, 2010 You can follow this conversation by subscribing to the comment feed for this post.

Combining the two in function form:


f=function(n) {a=0;b=1; sapply(1:n, function(i) {t=a+b;a<<-b;b<<-t;b/a})}


Barry's is still a wee bit shorter, though.

Using the bad algorithm brings it down to 42 characters :)

f=function(n) if(n<2) n else f(n-1)+f(n-2)

Ha! 41 characters and fast:

f=function(n){k=1:n;sum(choose(n-k,k-1))}

One of the benefits of R over other languages (at least for math) is the combination of vectorized functions, and the variety of built-in statistical algorithms. The above function uses both of these advantages.

we can then print with:
print(sapply(1:100,f))

But note that both this function and David's are wrong. They say that fib(0)==1. This is because in R, sequences can run backward (i.e. 1:0==c(1,0)). This is a common R gotcha. To fix this we need:

f=function(n){k=1:n;ifelse(n<1,0,sum(choose(n-k,k-1)))}

Which brings us back up to 55 characters

Did you know that any two numbers (at least one nonzero)can be used to initialize a Fibonacci sequence and the ratio will STILL converge to the golden ratio? And the convergence is fast!

fibrat=function(n,a=1,b=1){for(i in 1:n){t=b;b=a;a=a+t};a/b}
fibrat(20)
fibrat(20, 4, 17)
fibrat(20, 3.14159, 2.71828)

That's really interesting, Rick, didn't know that! Thanks! (And thanks also for the shout-out on your blog.)

another function for calculating the Fibonacci sequence, just for fun

fibo<-function(n){
if(n<=2){ c(0,1) } else { tmp<-fibo(n-1); c(0,tmp)+c(0,1,tmp[1:(n-2)])}
}

Ian fellows, not much of a challenge, the bad algorithm is even concise (33 chars) in C:

F(n){return n<2?n:F(n-1)+F(n-2);}

There is a good set of solutions on Rosetta Code.

That's another interesting and eye opening post , even if a bit advanced for those of us inexperienced in trading.
I would appreciate a post on the basics everyone must remember be it a newbie or apro.

The comments to this entry are closed.

## Search Revolutions Blog

Got comments or suggestions for the blog editor?
Email David Smith.