Friday, June 12, 2009

Example 7.1: Create a Fibonacci sequence

The Fibonacci numbers have many mathematical relationships and have been discovered repeatedly in nature. They are constructed as the sum of the previous two values, initialized with the values 1 and 1.

A pdf of this example is available here.

SAS
In SAS, we use the lag function (section 1.4.17, p. 22) to retrieve the last value.

data fibo;
do i = 1 to 10;
fib = sum(fib, lag(fib));
if i eq 1 then fib = 1;
output;
end;
run;
proc print data=fibo;
run;

This generates the following output:

Obs i fib
1 1 1
2 2 1
3 3 2
4 4 3
5 5 5
6 6 8
7 7 13
8 8 21
9 9 34
10 10 55

R
In R we can loop over an array to perform the same job.

len = 10
fibvals = numeric(len)
fibvals[1] = 1
fibvals[2] = 1
for (i in 3:len) {
fibvals[i] = fibvals[i-1] + fibvals[i-2]
}

This generates the following output:

> fibvals
[1] 1 1 2 3 5 8 13 21 34 55

5 comments:

Anonymous said...

You, sir, have just saved me 2 hours of merrily flopping about in the wondrous world of R, not having a single clue what was going on. So, thanks.

Anonymous said...

1. Explain what each part of the code means or does. [The part: for (i in 3:len) { fibvals[i] = fibvals[I 1] + fibvals[i-2]} is called a loop and helps in generation of outputs for the recurrence equations]

2. Why is there a '3' in the loop?

Ken Kleinman said...

Not sure what you mean to ask in #1. Everything before the for{} loop is just setting thing up.

The 3 in 3:len just means do this loop starting with the third item in the vector. So the first time we execute the loop, i = 3, and we sum fibvals[1] and fibvals[2].

Said another way, we initialize the sequence with the two 1s, and the remainder of the sequence we fill in with the loop.

Nuno said...

this is the function for fibonacci in r.

fibo<-function(x) {
len = x
x = numeric(len)
x[1] = 1
x[2] = 1
for (i in 3:len) {
x[i] = x[i-1] + x[i-2]
}
return(max(x))
}

Anonymous said...

Would you please explain why you coded different solutions in SAS and in R? If you use array in R, please use array also in SAS, so the solutions are more comparable.