1
$\begingroup$

Is there a way to generate the Fibonacci sequence with the Accumulate function?

$\endgroup$
  • $\begingroup$ Generate a specific number, generate up to a specific number ? $\endgroup$ – Sektor Aug 12 '15 at 17:57
  • $\begingroup$ @Sektor For example, generate the first 100 values of the Fibonacci sequence starting with { 0, 1 } $\endgroup$ – Tyler Durden Aug 12 '15 at 18:01
  • 6
    $\begingroup$ Ponder on the result of Accumulate[Fibonacci[Range[-1, 18]]] === Fibonacci[Range[20]]. You probably would be more interested in LinearRecurrence[]. $\endgroup$ – J. M. is away Aug 12 '15 at 18:03
16
$\begingroup$
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}
$\endgroup$
  • $\begingroup$ Nice! Wish I'd seen that myself. $\endgroup$ – Mr.Wizard Aug 13 '15 at 1:42
  • $\begingroup$ @Mr.Wizard, Thanks:) $\endgroup$ – xyz Aug 13 '15 at 2:50
  • $\begingroup$ Probably a good time for Nothing: Nest[Accumulate[{1, 0} ~Join~ #] &, {If[OddQ[n], 1, Nothing]}, Quotient[n, 2]] $\endgroup$ – J. M. is away Aug 13 '15 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$ – xyz Aug 14 '15 at 1:12
6
$\begingroup$

Well... I did use Accumulate!

First /@ NestList[{Last @ #, Last @* Accumulate @ #} &, {0, 1}, 10]
{0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.