首先,我想弄明白为什么我会有一个溢出错误。第一个函数"fibGen“很好,除非我给它一个非常大的第n个Fibonacci项。
#the golden ration function
def fibGen(num):
for number in range(0,num+1):
val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
print('{i:3}: {v:3}'.format(i=number, v=round(val)))
第二个函数"elemFib“将给我正确的答案,但如果数字超过1500,则会出错。
#the find element < Max number function
def elemFib(num):
for number in range(0,num+1):
val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
if val < num:
print('Fib({}): {}'.format(number, round(val)))
最后,"pythonic“函数的工作原理类似于"elemFib”函数,即使是一个很大的数字,也不会给我一个错误代码,,为什么呢?,我还试图让它打印斐波那契数字,就像第一个函数"fibGen“,但是不能让它像那样工作。
#Pythonic way
def pythonic(num):
a, b = 0,1
while a < num:
print(a, sep=" ", end=" ")
a, b = b, a+b
我的完整代码是你的评论:
import math
import time
#create the golden Ratio formula
golden_ratio = (1 + math.sqrt(5)) / 2
#the timer function
def clockTime(start_time):
print('\nRun Time:', time.time() - start_time)
#the golden ration function
def fibGen(num):
for number in range(0,num+1):
val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
print('{i:3}: {v:3}'.format(i=number, v=round(val)))
#the find element < Max number function
def elemFib(num):
for number in range(0,num+1):
val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
if val < num:
print('Fib({}): {}'.format(number, round(val)))
#Pythonic way
def pythonic(num):
a, b = 0,1
while a < num:
print(a, sep=" ", end=" ")
a, b = b, a+b
#display the Main Menu
def dispMenu():
print('---------------------Fibonacci Series ------------------\n')
print('(A) Print Fibonacci numbers to the nth term')
print('(B) Print Fibonacci numbers until element is less than Max number')
print('(C) pythonic print')
print('(Q) Quit the program\n')
def main():
# set boolean control variable for loop
loop = True
#Create while loop for menu
while loop:
#Display the menu
dispMenu()
#Get user's input
#choice = (input('Please make a selection: '))
#Get user's input
choice = input('Please make a selection: ').upper()
#Perform the selected action
if choice == 'A':
num = int(input("How many Fibonacci numbers should I print? "))
start_time = time.time()
fibGen(num)
clockTime(start_time)
elif choice == 'B':
num = int(input("the element should be less than? "))
start_time = time.time()
elemFib(num)
clockTime(start_time)
elif choice == 'C':
num = int(input('Pythonic Fibonacci series to the nth term? '))
start_time = time.time()
pythonic(num)
clockTime(start_time)
elif choice == 'Q':
print('\nExiting program, Thank you and Goodbye')
loop = False
else:
print('\nInvalid selection, try again\n')
main()
发布于 2019-05-28 19:07:28
一旦任何值变得太大,您的函数就会崩溃。这是因为在内部,Python用双打支持数字。
下面是重写为使用elemFib
s的elemFib
函数:
from decimal import Decimal
def elemFib(num):
for number in range(0,num+1):
val = golden_ratio ** Decimal(number) - (Decimal(1) - golden_ratio) ** Decimal(number) / Decimal(math.sqrt(5))
if val < num:
print('Fib({}): {}'.format(number, round(val)))
这不会像原版那样崩溃。我所做的就是用Decimal
对象替换所有数字。它们变慢了,但可以任意生长。
您的pythonic
函数没有以同样的方式崩溃的原因很简单,因为它没有创建疯狂的大数字,而另外两个函数的工作方式是将黄金比率提高到某个指数,这需要更大的数字。
发布于 2019-05-29 14:51:33
为了扩展上面的解释,python整数将自动提升为长数据类型,这样它就可以容纳任何数字。这个特性从python2.2开始就已经存在了。浮点数是有限的,它们不会自动提升为十进制类型。由于golden_ratio变量是一个浮点,除非手动更改类型,否则使用它的任何计算都是有限的。
https://www.python.org/dev/peps/pep-0237/
您可以使用sys.float_info
查找最大浮点数。
>>> import sys
>>> sys.float_info
sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)
在这里,您可以看到浮点数会导致OverflowError
,但是十进制或整数不会:
>>> 10.0 ** 309
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: (34, 'Numerical result out of range')
>>> Decimal(10.0) ** 309
Decimal('1.000000000000000000000000000E+309')
>>> 10 ** 309
1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000L
有趣的是,指数运算符**
引发OverflowError异常,但是乘法只返回inf
浮点值:
>>> 2 * (10.0 ** 308)
inf
>>> -2 * (10.0 ** 308)
-inf
>>> math.isinf(2 * (10.0 ** 308))
True
https://stackoverflow.com/questions/56279341
复制相似问题