刚接触Mathematica时,我尝试使用Do循环打印出前50个斐波纳契数,但似乎无法实现。我知道有一个内置的函数可以返回给定一个数字的斐波那契数列,但我想用一个Do循环来实现它。任何帮助都会非常感谢。
发布于 2017-02-07 09:54:51
像这样的东西
a = 0; b = 1; terms = {a, b};
Do[
{a, b} = {b, a + b};
terms = {terms, b},
{50 - 2}
];
Flatten@terms
我相信还有更花哨的方法。
发布于 2017-02-07 17:41:56
来自An Introduction to Programming with Mathematica,第178页。
第七章:递归
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,102334155,165580141,267914296,433494437,701408733,1134903170,1836311903,2971215073,4802675976,77742049,12586269025}
}
发布于 2017-02-07 22:31:42
使用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}
使用Reap/Sow
的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}
https://stackoverflow.com/questions/42076188
复制相似问题