Ping Ranier: Fibonacci number

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

•  Subject
• Author
• Posted on

Hi Ranier,

I am at a loss to know how

\$v0 + \$v1 || 1

becomes (https://en.wikipedia.org/wiki/Fibonacci_number )

F_n = F_ + F_,\!\,

with seed values[1][2]

F_1 = 1,\; F_2 = 1  or  F_0 = 0,\; F_1 = 1.

Is Perl really that sneaky?  Or where you pulling my leg?

-T

Re: Ping Ranier: Fibonacci number

You should run the program in a debugger or add print statements to see
what is going on.

--
Jim Gibson

Re: Ping Ranier: Fibonacci number

On 08/11/2015 06:30 PM, Jim Gibson wrote:

Possibly yes, but would it show me a Fibonacci chain?  How did
he seed it?  I am just curious as I know Rainer can be awfully
cleaver/smart.

Re: Ping Ranier: Fibonacci number

On 12/8/2015 00:06, T wrote:

#!/usr/bin/perl
use strict; use warnings; use feature qw/say/;

my \$fibo1 = FibonacciBuilder1(1,0,0);
my \$fibo0 = FibonacciBuilder0(1,0,0);

say \$fibo1->()    for 1..20;
say \$fibo0->()    for 1..20;

sub FibonacciBuilder1 {
my \$F1=\$_[0];
my \$F2=\$_[1];
my \$F3=\$_[2];

sub {
\$F3 = \$F2 + \$F1;
\$F1 = \$F2;
\$F2 = \$F3;
\$F3
}
}

sub FibonacciBuilder0 {
my \$F1=\$_[0];
my \$F2=\$_[1];
my \$F3=\$_[2];
my \$r;
sub {
\$r  = \$F3;
\$F3 = \$F2 + \$F1;
\$F1 = \$F2;
\$F2 = \$F3;
\$r
}
}

Re: Ping Ranier: Fibonacci number

It doesn't. The calculation is done the other way. I'm going through
this for a few steps.

Intially, \$v0 and \$v1 are undefined.

1st call to closure:

\$next = \$v0 + \$v1 || 1;

sets \$next to 1.

\$v0 = \$v1;

\$v0 remains undef.

\$v1 = \$next;

\$v1 now 1.

Return \$next == 1, the first number.

2nd call

\$next = \$v0 + \$v1 || 1;

Since \$v0 == undef and \$v1 == 1, \$next == 1.

\$v0 = \$v1;

Since \$v1 == 1, \$v0 == 1.

\$v1 = \$next;

\$v1 == 1. Return \$next == 1, next number.

3rd call

\$next = \$v0 + \$v1 || 1;

Since \$v0 == 1 and \$v1 == 1, \$next == 2.

\$v0 = \$v1;

\$v0 == 1

\$v1 = \$next;

\$v1 == 2, return \$next == 2, next number.

And so forth.

Generally, \$v0 is the 2nd-to-last number and \$v1 the last number. \$next
is set to the sum of both which is the next number. Afterwards,

\$v0 = \$v1;
\$v1 = \$next;

updates the state variables for the next call.

Since \$v0 and \$v1 are initially undef, their sum will be 0 which causes
the || 1 to be evaluated, supplying the first number.