2个问题,Python OverflowError:(34,“结果太大”)和错误的函数结果

时间:2019-05-23 16:19:00

标签: python-3.x error-handling runtime-error fibonacci

首先,我试图了解为什么会出现溢出错误。除非我给它一个第n个斐波那契大字,否则第一个函数“ fibGen”就可以正常工作。

    #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()

2 个答案:

答案 0 :(得分:1)

一旦任何值变得太大,您的函数就会崩溃。这是因为Python在内部使用doubles支持数字。

这是您的elemFib函数被重写为使用Decimal

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函数不会以相同的方式崩溃的原因仅仅是因为它不会创建疯狂的大数,而其他两个通过将黄金比例提高到某个指数而起作用,这需要大得多的数字

答案 1 :(得分:1)

为进一步解释上面的内容,python整数将自动提升为长数据类型,以便它可以容纳任何数字。自python 2.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