Wolfram mathematica fibonacci在mathematica中的应用

Wolfram mathematica fibonacci在mathematica中的应用,wolfram-mathematica,fibonacci,do-loops,Wolfram Mathematica,Fibonacci,Do Loops,刚接触Mathematica时,我尝试使用Do循环打印出前50个斐波那契数,但似乎无法使其工作。我知道有一个内置函数可以返回给定数字的斐波那契序列,但我想使用Do循环来实现它。任何帮助都将不胜感激。像这样的东西 a = 0; b = 1; terms = {a, b}; Do[ {a, b} = {b, a + b}; terms = {terms, b}, {50 - 2} ]; Flatten@terms 我相信还有更奇特的方法。摘自,第178页 第七章。递归 F[1] =

刚接触Mathematica时,我尝试使用Do循环打印出前50个斐波那契数,但似乎无法使其工作。我知道有一个内置函数可以返回给定数字的斐波那契序列,但我想使用Do循环来实现它。任何帮助都将不胜感激。

像这样的东西

a = 0; b = 1; terms = {a, b};

Do[
  {a, b} = {b, a + b};
  terms = {terms, b},
  {50 - 2}
];

Flatten@terms
我相信还有更奇特的方法。

摘自,第178页

第七章。递归

F[1] = 1;
F[2] = 1;
F[n_] := F[n - 2] + F[n - 1] /; n > 2
“事实证明,条件
/;n>2
是不必要的,因为Mathematica在更一般的规则(如
F[n]
)之前查找特定规则,如
F[1]=1
。下面是前十个斐波那契数的表。”

{1,1,2,3,5,8,13,21,34,55}

但是,为了获得足够的速度,还应使用:

{1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 701408733, 1134903170, 1836311903, 2971215073, 4807526976777874204912586269025}


使用
Nest

Nest[ Append[#, Total@#[[-2 ;;]]] &  , {1, 1}, 10]
{1,1,2,3,5,8,13,21,34,55,89,144}

使用
表格

Module[{last = 1, lastp = 1, next}, Join[{lastp, last},
  Table[next = last + lastp ; lastp = last ; last = next , {10}] ]]
{1,1,2,3,5,8,13,21,34,55,89,144}

Do
收割/播种

Reap[Module[{last = 1, lastp = 1 }, Sow[lastp]; Sow[last];
   Do[  {lastp, last} = {last, Sow[last + lastp]} ; , {10}] ]][[2, 1]]
{1,1,2,3,5,8,13,21,34,55,89,144}


实际上,您需要
嵌套
,但实际上您需要显示您遇到问题的代码。
Module[{last = 1, lastp = 1, next}, Join[{lastp, last},
  Table[next = last + lastp ; lastp = last ; last = next , {10}] ]]
Reap[Module[{last = 1, lastp = 1 }, Sow[lastp]; Sow[last];
   Do[  {lastp, last} = {last, Sow[last + lastp]} ; , {10}] ]][[2, 1]]