Is there a way to generate the Fibonacci sequence with the Accumulate
function?
2 Answers
$\begingroup$
$\endgroup$
4
fibSequences[n_?EvenQ] := Nest[Accumulate[Join[{1, 0}, #]] &, {}, n/2]
fibSequences[n_?OddQ] := Most@Nest[Accumulate[Join[{1, 0}, #]] &, {}, (n + 1)/2]
fibSequences[10]
{1, 1, 2, 3, 5, 8, 13, 21, 34, 55}
fibSequences[9]
{1, 1, 2, 3, 5, 8, 13, 21, 34}
-
$\begingroup$ Nice! Wish I'd seen that myself. $\endgroup$ Commented Aug 13, 2015 at 1:42
-
-
$\begingroup$ Probably a good time for
Nothing
:Nest[Accumulate[{1, 0} ~Join~ #] &, {If[OddQ[n], 1, Nothing]}, Quotient[n, 2]]
$\endgroup$ Commented Aug 13, 2015 at 17:12 -
$\begingroup$ @J. M., It is the first time for me to know the built-in
Nothing
.Thanks :) I searched the DOC, then I known that it was introduced in V10.2 $\endgroup$– xyzCommented Aug 14, 2015 at 1:12
$\begingroup$
$\endgroup$
Well... I did use Accumulate
!
First /@ NestList[{Last @ #, Last @* Accumulate @ #} &, {0, 1}, 10]
{0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55}
Accumulate[Fibonacci[Range[-1, 18]]] === Fibonacci[Range[20]]
. You probably would be more interested inLinearRecurrence[]
. $\endgroup$