Я пытаюсь создать программу на Python, которая применяет простое исключение по Гауссу с обратной установкой. Я сделал код следующим образом:
def gauss_elim_backwrds(A, b):
#if the input is not an np.array
if (type(A), type(b)) != np.array:
a = np.array(A)
be = np.array(b)
else:
a = A
be = b
#we obtain the augmented matrix
m = np.concatenate((a, be), axis=1)
#easy way to call the number of rows
n = m.shape[0]
#here starts gaussian elimination
for i in range(n-1):
#here's intended to find the smallest integer p such that a_pi is not zero
for j in range(i, n+1):
p = 0
api = m[p][i]
if api != 0:
break
else:
p += 1
continue
#as stablished in spanish, if such p doesn't exist, the the system doesn't have a unique solution an the program ends
if p > n:
result = 'No existe solución única.'
break
#here's intended to make row interchange to let a_pi be a pivot
if p != i:
temp = m[p, :]
m[p, :] = m[i, :]
m[i, :] = temp
#here I intend to make zero all the row elements that are below the pivot
for j in range(i+1, n+1):
mji = m[j][i]/m[i][i]
m[j, :] = m[j, :]-mji*m[i, :]
#another criteria for knowing if the system doesn't have solution is if the n,n'th element of the matriz A now reduced is zero
if m[n][n] == 0:
result = 'No existe solución única.'
#I intended to make backwards sustitution here
xnn = m[n][n+1]/m[n][n]
x = [xnn]
for i in range(n-1, step=-1):
coeftemp=[m[i][j]*x[j] for j in range(i+1,n+1)]
xi = (m[i][n+1]-sum(coeftemp)/m[i][i])
x.append(xi)
if result != 'No existe solución única.':
result = reversed(x)
return result
m_prueba = np.array([[4, -1, 1], [2, 5, 2], [1, 2, 4]])
b_prueba = np.array(([8], [3], [11]))
print(gauss_elim_backwrds(m_prueba, b_prueba))
но я получаю ошибку:
File "C:/Users/Armando Rosas/PycharmProjects/untitled/Tarea 3.py", line 49, in <module>
print(gauss_elim_backwrds(m_prueba, b_prueba))
File "C:/Users/Armando Rosas/PycharmProjects/untitled/Tarea 3.py", line 30, in gauss_elim_backwrds
mji = m[j][i]/m[i][i]
IndexError: index 3 is out of bounds for axis 0 with size 3
Так что я не могу увидеть, работает ли код mu. Я рассчитал вручную, что решение моей тестовой системы будет x=np.array[[1], [-1], [3]]