Anonymous user
Fibonacci sequence: Difference between revisions
→{{header|Python}}: Rearranged iterative +/- to iterative section
PatGarrett (talk | contribs) (→{{header|TI-83 BASIC}}: Add the natural way) |
(→{{header|Python}}: Rearranged iterative +/- to iterative section) |
||
Line 9,086:
=={{header|Python}}==
===Iterative positive and negative===▼
<lang python>def fib(n,x=[0,1]):▼
for i in range(abs(n)-1): x=[x[1],sum(x)]▼
return x[1]*pow(-1,abs(n)-1) if n<0 else x[1] if n else 0▼
for i in range(-30,31): print fib(i),</lang>▼
Output:▼
<pre>▼
-832040 514229 -317811 196418 -121393 75025 -46368 28657 -17711 10946 -6765 4181 -2584 1597 -987 ▼
610 -377 233 -144 89 -55 34 -21 13 -8 5 -3 2 -1 1 0 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▼
</pre>▼
===Analytic===
Binet's formula:
Line 9,125 ⟶ 9,113:
return fib</lang>
▲====Iterative positive and negative====
▲<lang python>def fib(n,x=[0,1]):
▲ for i in range(abs(n)-1): x=[x[1],sum(x)]
▲ return x[1]*pow(-1,abs(n)-1) if n<0 else x[1] if n else 0
▲for i in range(-30,31): print fib(i),</lang>
▲Output:
▲<pre>
▲-832040 514229 -317811 196418 -121393 75025 -46368 28657 -17711 10946 -6765 4181 -2584 1597 -987
▲610 -377 233 -144 89 -55 34 -21 13 -8 5 -3 2 -1 1 0 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
▲</pre>
===Recursive===
<lang python>def fibRec(n):
|