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

knpiaxh1  于 2023-02-14  发布在  Python
关注(0)|答案(2)|浏览(269)

首先,我试图理解为什么我会得到一个溢出错误。第一个函数“fibGen”工作正常,除非我给予它一个疯狂的大第n斐波那契项。

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

w8f9ii691#

一旦某个值变得太大,函数就会崩溃,这是因为Python内部用doubles支持数字。
下面是为使用Decimal 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函数不会以同样的方式崩溃的原因很简单,因为它不会产生疯狂的大数字,而其他两个函数的工作原理是将黄金分割率提高到某个指数,这需要更大的数字。

gj3fmq9x

gj3fmq9x2#

进一步解释一下,python integers会自动升级为long数据类型,这样它就可以容纳任何数字。这个特性从python 2.2就已经存在了。浮点数是有限的,并且它们不会自动升级为Decimal类型。由于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

相关问题