高斯消除Python(值错误)

时间:2018-07-24 22:20:27

标签: python numpy valueerror

大家晚上好

我正在尝试在python中实现高斯消除算法。虽然,我相信实现是正确的(已在Octave上进行了测试),但是我似乎遇到了Value错误,如果不稍加改变采用的方法的逻辑,我似乎无法解决。请在下面找到代码和相关的错误消息。

import numpy as np

def gauss(A,b):
n = len(A)
A = np.array([A,b])

for i in range(n-1):
    p=i
    while (p<=n-1) and (A[p,i]==0):
        p=p+1
    if p == n:
        print('No unique solution.')
        x = []
        return x
    if p != i:
        T = A[i,:]
        A[i,:] = A[p,:]
        A[p,:] = T
    for j in range(i+1,n):
        m=A[j,i]/A[i,i]
        for k in range(i,n+1):
            A[j,k]=A[j,k]-m*A[i,k]

if A[n-1,n-1] == 0:
    print("No unique solution")
    x=[]
    return x
x = [0]*n
x[n-1] = A[n-1,n]/A[n-1,n-1]

for i in range(n-2,-1,-1):
    tot = 0

    for j in range(i+1,n):
        tot = tot + A[i,j]*x[j]
    x[i] = (A[i,n] - tot)/A[i,i]

for i in range(n):
    print("x("+str(i+1)+") :",x[i])

值错误由while语句中的条件产生。它说明了具有多个元素的数组的真值的歧义性。但是,我认为索引将消除此错误。请帮忙。

gauss(A,b)
Traceback (most recent call last):

File "<ipython-input-49-3f9a1b401722>", line 1, in <module>
gauss(A,b)

File "C:/Users/foo bar/Documents/Programming Projects/Python/Data 
Analysis/gauss.py", line 16, in gauss
while (p<=n-1) and (A[p,i]==0):

ValueError: The truth value of an array with more than one element is 
ambiguous. Use a.any() or a.all()      

0 个答案:

没有答案