简体   繁体   English

尝试运行具有更高 integer 值 (n > 20) 的代码时出错

[英]Error when trying to run code with a higher integer value (n > 20)

I'm a beginner programmer that's trying to write a program that requests an integer n within some defined limits and then computes certain mathematical functions and displays them in a formatted table.我是一名初学者程序员,正在尝试编写一个程序,该程序在某些定义的限制内请求 integer n,然后计算某些数学函数并将它们显示在格式化表中。

At the moment I have the limits set so that (0 <= n <= 10000) but this might be the issue for now.目前我已经设置了限制,以便 (0 <= n <= 10000) 但这可能是现在的问题。

Here's my code:这是我的代码:


#---------------------------Handling Exceptions------------------------------#
# this deals with the user typing in letters or numbers outside of the limit
# set
def inputNumber():
    while True:
        try:
            userInput = int(input('Please enter an integer (0<=n<=10000): '))
            while (userInput < 0) or (userInput > 10000):
                print('This value is outside of the limits! Please try again.')
                userInput = int(input('Please enter an integer: '))
        except ValueError:
            print('You did not enter a valid integer! Please try again.')
            continue
        else:
            return userInput
#---------------------------end Handling Exceptions--------------------------#

#--------------------------Main Program Start--------------------------------#

import numpy as np # importing the numpy library

#inform the user what the program does
print('\nThis program asks the user to enter an integer value n and computes')
print(' sum(n), exp(n), n! and ln(n). It then displays the results in a table')

# set the variable n to user defined function
n = inputNumber()



# putting titles for each output column
title1, title2, title3, title4, title5 = 'n', 'sum(1..n)', 'exp(n)', 'n!', \
    'ln(n!)'

# print in desired format
print('\n{0:>8}'.format(title1),
      '{0:>10}'.format(title2),
      '{0:>18}'.format(title3),
      '{0:>20}'.format(title4),
      '{0:>10}'.format(title5))

# setting up operators for sum and factorial functions using numpy:
def factorial(n): # function for factorial operator
   if n == 1:
       return n
   elif n == 0:
       return 1
   else:
       return n*factorial(n-1)
   
def nsum(n): # this is the summing function over n
    if n == 0:
        return 0
    else:
        return int(n*(n + 1)/2) # had to convert string to integer format
    # reference: https://brilliant.org/wiki/sum-of-n-n2-or-n3/

    

# evaluate and print in for loop
for i in range(0, n+1):
    n_int = 0 + i
    sum_n = nsum(n_int)
    exp_n = np.exp(n_int)
    fact_n = factorial(n_int)
    logfact_n = np.log(factorial(n_int))
    
    print('{0:>8d}'.format(n_int),
          '{0:>10d}'.format(sum_n),
          '{0:>18.3f}'.format(exp_n),
          '{0:>20d}'.format(fact_n),
          '{0:>10.3f}'.format(logfact_n))

#--------------------------Main Program End----------------------------------#

The code runs fine and it is able to handle the exceptions but I get an AttributeError when I put n = 21.代码运行良好,并且能够处理异常,但是当我输入 n = 21 时出现 AttributeError。

AttributeError: 'int' object has no attribute 'log'


The above exception was the direct cause of the following exception:

Traceback (most recent call last):

  File "C:\Users\pjjan\OneDrive\Documents\Python\forLoop3_19318421.py", line 79, in <module>
    logfact_n = np.log(factorial(n_int))

TypeError: loop of ufunc does not support argument 0 of type int which has no callable log method

Here is the full output:这是完整的 output:

This program asks the user to enter an integer value n and computes
 sum(n), exp(n), n! and ln(n). It then displays the results in a table

Please enter an integer (0<=n<=10000): 21

       n  sum(1..n)             exp(n)                   n!     ln(n!)
       0          0              1.000                     1      0.000
       1          1              2.718                     1      0.000
       2          3              7.389                     2      0.693
       3          6             20.086                     6      1.792
       4         10             54.598                    24      3.178
       5         15            148.413                   120      4.787
       6         21            403.429                   720      6.579
       7         28           1096.633                  5040      8.525
       8         36           2980.958                 40320     10.605
       9         45           8103.084                362880     12.802
      10         55          22026.466               3628800     15.104
      11         66          59874.142              39916800     17.502
      12         78         162754.791             479001600     19.987
      13         91         442413.392            6227020800     22.552
      14        105        1202604.284           87178291200     25.191
      15        120        3269017.372         1307674368000     27.899
      16        136        8886110.521        20922789888000     30.672
      17        153       24154952.754       355687428096000     33.505
      18        171       65659969.137      6402373705728000     36.395
      19        190      178482300.963    121645100408832000     39.340
      20        210      485165195.410   2432902008176640000     42.336
AttributeError: 'int' object has no attribute 'log'


The above exception was the direct cause of the following exception:

Traceback (most recent call last):

  File "C:\Users\pjjan\OneDrive\Documents\Python\forLoop3_19318421.py", line 79, in <module>
    logfact_n = np.log(factorial(n_int))

TypeError: loop of ufunc does not support argument 0 of type int which has no callable log method

I don't know how to resolve the issue and I'm using Python 3.8 for anyone wondering.我不知道如何解决这个问题,我正在为任何想知道的人使用 Python 3.8。 I hope someone can help.我希望有人能帮帮忙。 Thank you and sorry for any trivial mistakes I've made in the code.谢谢你,对我在代码中犯的任何小错误深表歉意。 I'm very much a beginner.我是个初学者。

Factorial gets very big, very fast.阶乘变得非常大,非常快。 After 20 (20, ~= 2e18), numpy switches to a different integer formulation that doesn't have a log method.在 20 (20, ~= 2e18) 之后, numpy切换到没有log方法的不同 integer 公式。

You can either use higher precision, or you can take advantage of the fact that multiplying log is the same as adding outside of it:您可以使用更高的精度,也可以利用对log相乘与在其外部相加相同的事实:

logfact_n += np.log(i) 

(You'll have to fudge the first term since the log of 0 is undefined) (你必须捏造第一个术语,因为 0 的日志未定义)

Proof:证明:

np.cumsum(np.log(np.arange(20)+1))
Out[]: #same as your results
array([ 0.        ,  0.69314718,  1.79175947,  3.17805383,  4.78749174,
        6.57925121,  8.52516136, 10.6046029 , 12.80182748, 15.10441257,
       17.50230785, 19.9872145 , 22.55216385, 25.19122118, 27.89927138,
       30.67186011, 33.50507345, 36.39544521, 39.33988419, 42.33561646])

The problem is that your 'int' grows so fast that produces an overflow.问题是你的'int'增长得如此之快以至于产生了溢出。 Try with long or double formats:尝试使用长格式或双格式:

# evaluate and print in for loop
for i in range(0, n+1):
    n_int = np.longdouble(0 + i)
    sum_n = nsum(n_int)
    exp_n = np.exp(n_int)
    fact_n = factorial(n_int)
    logfact_n = np.log(factorial(n_int))
    
    print('{0:>8f}'.format(n_int),
          '{0:>10f}'.format(sum_n),
          '{0:>18.3f}'.format(exp_n),
          '{0:>20f}'.format(fact_n),
          '{0:>10.3f}'.format(logfact_n))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试运行基于 PysimpleGUIqt 的代码时出错 - Error when trying to run code based on PysimpleGUIqt 尝试运行我的 tensorflow 代码时出错 - error when trying to run my tensorflow code 尝试在 pycharm 上运行代码以及在 cmd 中输入 pip 时出错 - error when trying to run a code at pycharm and when typing pip at the cmd 尝试在 Visual Studio Code (Flatpak) 中运行 PyAudio 时出现错误消息 - Error message when trying to run PyAudio in Visual Studio Code (Flatpak) 当我尝试运行代码时,它会出错 - When I am trying to run the code it gives error 尝试运行代码时出现 Beautifulsoup4 语法错误 - Beautifulsoup4 syntax error when trying to run code 我正在尝试运行现有代码,但是当我尝试运行代码时,错误显示“没有名为 fetch 的模块” - I am trying to run and existing code but when I try to run the code the error shows “No module named fetch” 尝试运行pip时出错 - Error when trying to run pip 我试图运行代码,但我仍然得到相同的错误值错误无效文件或缓冲区 - i was trying to run the code and im still getting same error value error invalid file or buffer 尝试运行 Jupyter-Dash 并出现“需要 integer”错误 - Trying to run Jupyter-Dash and getting "an integer is required" error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM