Mathematica的新手,我试图使用Do循环打印出前50个Fibonacci数字,但似乎无法使其工作。我知道有一个内置函数返回给定数字的Fibonacci序列,但我想用Do循环实现它。任何帮助都会非常感激。
答案 0 :(得分:2)
像这样的东西
a = 0; b = 1; terms = {a, b};
Do[
{a, b} = {b, a + b};
terms = {terms, b},
{50 - 2}
];
Flatten@terms
我确信有更好的方式。
答案 1 :(得分:1)
来自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[1] = 1
这样的更一般规则之前查找F[n]
之类的特定规则。这是前十个斐波那契数字的表格。"
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,102325155,165580141, 267914296,433494437,701408733,1134903170,1836311903,2971215073, 4807526976,7778742049,12586269025}
答案 2 :(得分:0)
使用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}