我偶然遇到了以下高斯消除代码。我正在使用Python 3笔记本,但是在运行它时遇到以下错误,我正在寻求一些有关解决这些错误的帮助,谢谢!
这是我遇到的错误,我不太确定如何解决这些错误,我正在寻求一些帮助!
NameError Traceback (most recent call last)
<ipython-input-15-6b9df16115dd> in <module>()
67 b = np.array([[14.],[4.],[2.],[2.]])
68
---> 69 print (GENP(np.copy(A), np.copy(b)))
70
71 print (GEPP(A,b))
<ipython-input-15-6b9df16115dd> in GENP(A, b)
25 raise ValueError("Invalid argument: incompatible sizes between A & b.", b.size, n)
26
---> 27 for pivot_row in xrange(n-1):
28
29 for row in xrange(pivot_row+1, n):
NameError: name 'xrange' is not defined
,这是我找到的代码:
import numpy as np
def GENP(A, b):
'''
Gaussian elimination with no pivoting.
% input: A is an n x n nonsingular matrix
% b is an n x 1 vector
% output: x is the solution of Ax=b.
% post-condition: A and b have been modified.
'''
n = len(A)
if b.size != n:
raise ValueError("Invalid argument: incompatible sizes between A & b.", b.size, n)
for pivot_row in xrange(n-1):
for row in xrange(pivot_row+1, n):
multiplier = A[row][pivot_row]/A[pivot_row][pivot_row]
#the only one in this column since the rest are zero
A[row][pivot_row] = multiplier
for col in xrange(pivot_row + 1, n):
A[row][col] = A[row][col] - multiplier*A[pivot_row][col]
#Equation solution column
b[row] = b[row] - multiplier*b[pivot_row]
print (A)
print (b)
x = np.zeros(n)
k = n-1
x[k] = b[k]/A[k,k]
while k >= 0:
x[k] = (b[k] - np.dot(A[k,k+1:],x[k+1:]))/A[k,k]
k = k-1
return x
if __name__ == "__main__":
A = np.array([[1.,-1.,1.,-1.],[1.,0.,0.,0.],[1.,1.,1.,1.],[1.,2.,4.,8.]])
b = np.array([[14.],[4.],[2.],[2.]])
print (GENP(np.copy(A), np.copy(b)))
print (GEPP(A,b))
答案 0 :(得分:0)
xrange
在python3中不存在。请改用range
。