gpt4 book ai didi

python-3.x - ZeroDivisionError : float division by zero in list elements division

转载 作者:行者123 更新时间:2023-12-03 08:39:11 24 4
gpt4 key购买 nike

每当我运行此代码时,我都会在下面提到的行中得到零除错误。同样,当列表不是用户输入时,也不会发生该错误。错误如何出现,我该如何解决?

n=int(input("Dimension of the coefficient matrix: "))

a=[[0]*n]*n
for i in range(n):
for j in range(n):
print("Enter (",i,",",j,") coefficient:")
a[i][j]=float(input())

b=[float(input("Enter RHS :")) for i in range(n)]
'''
a=[
[3,-2,5,0],
[4,5,8,1], ( not getting the error when the lists are not user input)
[1,1,2,1],
[2,7,6,5]
]
b=[2,4,5,7]
n=len(b)
'''

for k in range(n-1):
for i in range(k+1,n):
if a[i][k]==0: continue
factor=a[k][k]/a[i][k]
for j in range(k,n):
a[i][j]=a[k][j]-a[i][j]*factor
b[i]=b[k]-b[i]*factor

for i in range(n):
print(a[i])

x=([(0)]*n)


x[n-1]=b[n-1]/a[n-1][n-1] '''getting the error in this line'''

for i in range(n-2,-1,-1):
sum=0
for j in range(i+1,n):
sum+= a[i][j]*x[j]
x[i]=b[i]-sum/a[i][i] '''also in this line'''
for i in range(n):
print("x(",i,") = ",x[i])

最佳答案

这是因为创建零矩阵的方式:a = [[0]*n]*n。您只需重复n乘以内部列表[0]*n即可,但不复制它。因此,您具有指向同一列表的n链接。通过以下示例可以很容易理解:

In [1]: a = [[0]*2]*2

In [2]: a
Out[2]: [[0, 0], [0, 0]]

In [3]: a[1][1] = 1

In [4]: a
Out[4]: [[0, 1], [0, 1]]
您可以执行以下操作: a = [[0]*n for _ in range(n)]或者只是使用 numpy来更灵活地处理数组:
from numpy import zeros
a = zeros((n, n))

关于python-3.x - ZeroDivisionError : float division by zero in list elements division,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63672629/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com