« Generating the nth roots of a number | Main | Macros: Prime numbers »

September 06, 2004

A Simple Macro: Fibonacci Numbers

When learning a new (computer) language - it is important to have a good mastery of the basics. Developing simple functions like this is what is called for here.

Function Fibonacci(Val As Integer) As Long
Dim I As Integer
Fibonacci = 1
For I = 1 To Val
Fibonacci = Fibonacci * I
Next I
End Function

We can now call our newly created function from the spreadsheet - just like the builtin OOo Calc functions.

fibonacci.jpg

Posted by Dave at September 6, 2004 04:34 AM

Comments

I hate to be pedantic (actually, no. I love it).

However, your Fibonacci number macro doesn't return Fibonacci numbers, it returns factorials.

A factorial is represented by the symbol !, and is the product of an integer and every natural number preceeding it (0 and negative numbers aren't natural numbers). So 1! = 1, 2! = 2, 3!=6 etc

A Fibonacci sequence is one where Un+2=Un+1+Un

The most common quoted Fibonacci sequence goes 1,1,2,3,5,8,13,21,34,55 etc...

Otherwise, keep up the good work!

Posted by: Tim Clarke at February 25, 2005 08:23 PM

These are not Fibonacci numbers; they are the factorials. Fibonacci numbers are generated like this:

fib(1) = fib(2) = 1
for n > 2, fib(n) = fib(n-1) + fib(n-2)

Posted by: Ed Martin at February 25, 2005 10:52 PM

¿What about 0,1,1,2,3,5,8,13,21,34,55?

Function Fibonacci(Val As Integer) As Long
Dim I As Integer
Fibonacci = 1
For I = 0 To Val-2
Fibonacci = Fibonacci + I
Next I
Fibonacci = Fibonacci + 1
End Function

Posted by: Jonatan de la Torre at July 12, 2005 06:12 AM

This is how I'd make Fibonacci function for calc.
It does work fine.

REM ***** BASIC *****
REM ***** Fibonacci *****
REM ***** Cálcula el numero fibonacci de orden Val ***
Function fib(byval Val As Integer) As Double
Dim I As Integer
Dim fib2 As Double
Dim fib1 As Double
fib = 0
fib2 = 0
fib1 = 1
If Val < 2 Then
IIf (Val = 0, fib = fib2 , fib = fib1)
Goto Fin
End If
For I = 2 To Val
fib = fib2 + fib1
fib2 = fib1
fib1 = fib
Next I
Fin:
End Function

Posted by: Jonatan de la Torre at July 20, 2005 08:51 AM

Post a comment




Remember Me?