1
$\begingroup$

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

$\endgroup$
3
  • $\begingroup$ Generate a specific number, generate up to a specific number ? $\endgroup$
    – Sektor
    Commented Aug 12, 2015 at 17:57
  • $\begingroup$ @Sektor For example, generate the first 100 values of the Fibonacci sequence starting with { 0, 1 } $\endgroup$ Commented Aug 12, 2015 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$ Commented Aug 12, 2015 at 18:03

2 Answers 2

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$
4
  • $\begingroup$ Nice! Wish I'd seen that myself. $\endgroup$
    – Mr.Wizard
    Commented Aug 13, 2015 at 1:42
  • $\begingroup$ @Mr.Wizard, Thanks:) $\endgroup$
    – xyz
    Commented Aug 13, 2015 at 2:50
  • $\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$
    – xyz
    Commented Aug 14, 2015 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 and acknowledge you have read our privacy policy.

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