我试图打印Fibonacci序列,并且在第600个术语后总是返回一个溢出错误。错误34,结果太大
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')
请注意,这实际上不会打印斐波那契序列,它会打印出一个粗略的斐波那契序列的近似值 - 它会以打印实际序列效率较低的方式进行打印。那真的是你想要的吗? – abarnert 2014-10-21 22:33:00
此外,由于您使用递归伪造了一个循环,而不是仅使用循环,所以一旦解决了这个问题,您将在第1000次尝试打印斐波那契数时发生'RecursionError'。 – abarnert 2014-10-21 22:33:28