in reply to Re^2: fibonacci numbers using subroutine?
in thread fibonacci numbers using subroutine?
recursive function follows better the mathematical definition and is easier to implement (no useless loop).Fibonacci is a prime example why recursion can be very, very bad. For instance, your fibonacci(25) call results in 242785 calls to fibonacci. This doesn't scale.
Even the most naïve loop implementation only execute its body 25 times. And it only takes two lines:
And there's a formula that does the calculation in constant time.†:my ($f, $fn) = (0, 1); ($f, $fn) = ($fn, $f + $fn) for 1 .. 25; print $f;
And since 1 < $PHI < 2, that can be written as:my $PHI = (1 + sqrt(5)) / 2; Fibonnaci(N) = ($PHI ** $N - (1 - $PHI) ** $N) / sqrt(5);
The only disadvantage the closed form has that for (on a 64 bit platform), for values > 84, the closed form suffers from rounding errors. But then, for values > 93, the result no longer fits in 64 bits integers, so precision is lost either way.Fibonnaci(N) = int(0.5 + $PHI ** $N / sqrt(5))
† That assuming all arithmetic operations take constant time. This isn't quite true - it shuffles the size of the numbers under the carpet. There's a log(N) factor assumed (log(N) is the number of bits needed to store N).
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: fibonacci numbers using subroutine?
by alexbio (Monk) on Aug 20, 2010 at 21:17 UTC | |
by JavaFan (Canon) on Aug 20, 2010 at 22:10 UTC | |
by alexbio (Monk) on Aug 22, 2010 at 10:35 UTC |