132

Stepinkin
mail@pastecode.io avatar
unknown
python
2 years ago
1.9 kB
1
Indexable
Never
import numpy as np
matrix = np.array([[9.00, 2.01, 0.13, -1.50],
                   [1.85, 5.05, 0.60,  0.80],
                   [0.12, 0.75, 3.00,  0.20]])


def PrivedenieKTreugol(matrix):
    for row_number, row in enumerate(matrix):
        mainel = row[row_number]
        if mainel!=0:          
            row /= mainel      
            for lower_row in matrix[row_number + 1:]:   
                el = lower_row[row_number]
                lower_row -= el * row
        else:                   
            for i in range(matrix.shape[0]-1):
                if (i<=2):
                    matrix[[row_number,row_number+i]]=matrix[[row_number+i,row_number]] 
                    mainel = row[row_number]
                    if mainel!=0:   
                        row /= mainel
                        for lower_row in matrix[row_number + 1:]:
                            el = lower_row[row_number]
                            lower_row -= el * row
                        break
                        
        if mainel==0:   
            raise ValueError("Матрица несовместна")




def Obratniy_hod(matrix):
    row_count = matrix.shape[0]
    x=[None]*row_count
    for i in range(row_count-1, -1,-1):
        x[i]=matrix[i,-1]-np.dot(matrix[i, i+1:row_count], x[i+1:])

    return(x)

PrivedenieKTreugol(matrix)
print("Мое решение")     
for a, i in enumerate(Obratniy_hod(matrix)):
    print(f"x{a + 1} =", i)

print("///////////////////////////\n")
matrix1 = np.array([[9.00, 2.01, 0.13],
                   [1.85, 5.05, 0.60],
                   [0.12, 0.75, 3.00]])

b= np.array([[ -1.50],[  0.80],[  0.20]])
print("матрица на ответ")
print(np.dot(matrix1,Obratniy_hod(matrix)),'\n')
print("///////////////////////////\n")
print("Ответ встроенной библиотеки numpy")
print(np.linalg.solve(matrix1, b ))