【问题标题】:Python int too large to convert to C long code needs fixPython int 太大而无法转换为 C 长代码需要修复
【发布时间】:2015-04-01 03:02:07
【问题描述】:

大家好,我在运行代码时不断收到此错误

Traceback (most recent call last):
  File "Jacobi.py", line 93, in <module>
    limit, guess, statement = jacobi(sys.argv[1], sys.argv[2])
  File "Jacobi.py", line 65, in jacobi
    guess[0, i] = guess2[0, i]
OverflowError: Python int too large to convert to C long

我在下面发布了我的代码,有人能快速解决吗?只是在随机情况下,它不会一直这样做。有人知道为什么吗?

def jacobi(file_name, tolIn):

if file_name is None:
    exit()

#Turns file into one big matrix
A = np.loadtxt(file_name, dtype=int64, delimiter=" ")
aRows = int(A.shape[0])
aCols = int(A.shape[1])
bdim = (aRows, 1)
b = np.zeros(bdim)

s = raw_input("Please provide list of your guess values separated by spaces, e.g. 1 2 3: ")
guess = np.matrix(s)

#Creates nx1 b matrix
for j in range(0, aRows):
   b[j,0] = float(A[j, aCols-1])

#创建一个矩阵 elim = [aCols-1] N = np.delete(A, elim, 1) A = N

for i in range (0, A.shape[0]):
    for k in range (0, A.shape[0]):
        A[i,k] = round((A[i,k]),7)
print(A)
print ('\n')
print(b)


tol = float(tolIn)

#Sets intial previous guess so loop does not stop first try
prevGuess = np.zeros((1, aRows))
for i in range (0, aRows):
    prevGuess[0,i] = 1000


guess2 = np.zeros((1, aRows))
limit = 0
aRows = int(A.shape[0])
aCols = int(A.shape[1])


while ((np.linalg.norm(guess - prevGuess) > tol) and limit < 100):
    for j in range (0, aRows):
        guess2[0,j] = b[j,0]
        for i in range (0, aCols):
            if (i != j):
                guess2[0,j] = round((guess2[0,j] -(A[j,i]) * (guess[0,i])), 7)
        guess2[0,j] = round((guess2[0,j] / A[j,j]), 7)

    for i in range(0, aCols):
            prevGuess[0,i] = guess[0, i]
    for i in range(0, aCols-1):
            guess[0, i] = round((guess2[0, i]), 7)
    guess2 = np.zeros((1, aCols))
    limit = limit + 1

#answers mod 2 to get real answers
#for i in range(0,aCols):
#    guess[0,i] = guess[0,i]%2

#print ('\n')
#print(limit)
#print ('\n')
#print (guess)
#print ('\n')

【问题讨论】:

    标签: python matrix overflow


    【解决方案1】:

    我相信range() 要求最大数字包含在 c 整数范围内。如果你想解决这个问题,你可以使用itertools.count()。它从 0(或您作为参数传递的数字)开始并永远计数(或直到您中断)。

    例子:

    for i in itertools.count():
        if i == 10:
            break
        print i
    

    文档:https://docs.python.org/2/library/itertools.html#itertools.count

    【讨论】:

    • 但它适用于其他代码,它与我输入的文件有关。一个有小数,另一个只有直整数。
    • 不幸的是,问题中没有描述你的很多代码,所以我只能猜测每个部分的作用。我自己也无法测试。您能否举例说明输入、输出和您的期望?这将帮助我更好地理解。
    • 输入是一个 .dat 文件,其中包含我使用 load.txt 加载到矩阵中的值。我使用了带有直整数的文件,它工作得很好,我有一个带有长小数的文件,它会抛出该消息。我将用我的整个代码编辑帖子。
    • 您是否手动检查过您的输入是否小于整数的大小?该大小将根据您的 python 安装是 32 位或 64 位而有所不同。
    猜你喜欢
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    • 2016-12-29
    • 1970-01-01
    • 1970-01-01
    • 2015-10-12
    • 2016-01-09
    • 1970-01-01
    相关资源
    最近更新 更多