【问题标题】:fibonacci using mathematica使用数学的斐波那契
【发布时间】:2017-02-06 19:56:47
【问题描述】:

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

【问题讨论】:

标签: wolfram-mathematica fibonacci do-loops


【解决方案1】:

类似的东西

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

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

Flatten@terms

我相信还有更好的方法。

【讨论】:

    【解决方案2】:

    来自An Introduction to Programming with Mathematica,第 178 页。

    第 7 章递归

    F[1] = 1;
    F[2] = 1;
    F[n_] := F[n - 2] + F[n - 1] /; n > 2
    

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

    Table[F[i], {i, 1, 10}]
    

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

    但是,为了获得足够的速度,也请使用memoization:

    F[1] = 1;
    F[2] = 1;
    F[n_] := F[n] = F[n - 2] + F[n - 1]
    
    Table[F[i], {i, 1, 50}]
    

    {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、 4807526976、7778742049、12586269025}

    【讨论】:

      【解决方案3】:

      使用Nest

      Nest[ Append[#, Total@#[[-2 ;;]]] &  , {1, 1}, 10]
      

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

      使用Table

      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/Sow:

      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}

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-06-05
        • 2014-05-23
        • 2014-05-03
        • 1970-01-01
        • 2020-01-18
        • 2012-12-29
        相关资源
        最近更新 更多