【发布时间】:2014-10-21 22:11:18
【问题描述】:
我正在尝试打印斐波那契数列,但它总是在第 600 项之后返回溢出错误。
def fib():
import math
from math import sqrt
print "\nFibonacci Sequence up to the term of what?"
n=raw_input(prompt)
if n.isdigit():
if int(n)==0:
return 0
elif int(n)==1:
return 1
else:
n_count=2
print "\n0\n1"
while n_count<int(n):
fib=int(((1+sqrt(5))**n_count-(1-sqrt(5))**n_count)/(2**n_count*sqrt(5)))
print fib
n_count+=1
fib()
else:
print "\nPlease enter a number."
fib()
fib()
当我运行这个时:
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
fib()
File "<pyshell#20>", line 15, in fib
fib=int(((1+sqrt(5))**n_count-(1-sqrt(5))**n_count)/(2**n_count*sqrt(5)))
OverflowError: (34, 'Result too large')
【问题讨论】:
-
请注意,这实际上不会打印斐波那契数列,它会打印斐波那契数列的粗略近似值——而且它会以一种比打印实际序列效率低的方式来打印。这真的是你想要的吗?
-
另外,因为你用递归来伪造一个循环而不是仅仅使用一个循环,一旦你解决了这个问题,你就会在第 1000 次尝试打印时得到一个
RecursionError斐波那契数。
标签: python python-2.7 overflow python-2.x fibonacci