高斯消元法python编程_高斯消元法的Python实现

高斯消元法

节约内存的算法:

例1:用高斯消元法求解线性方程组:

# -*- coding: utf-8 -*-

"""

求解线性方程组:

[12 -3 3] [x1] = [15]

[18 -3 1] [x2] = [15]

[-1 2 1] [x3] = [ 6]

@athor: morxio

"""

import sys

import numpy as np

def GassianEliminationSolver(a):

n = a.shape[0]

for k in range(0,n-1): #0,1,2,...,n-2

print(a)

if np.abs(a[k,k]) < 1e-6:

print("主元素过小")

sys.exit(1)

for i in range(k+1,n): #k+1, k+2, ..., n-1

a[i,k] /= a[k,k]

for j in range(k+1,n+1):

a[i,j] -= a[i,k] * a[k,j]

#a[n-1,n] /= a[n-1][n-1]

for i in range(n-1, -1, -1):

sum = 0

for j in range(i+1,n):

sum += a[i,j] * a[j,n]

a[i,n] = (a[i,n] - sum) / a[i,i]

return a[:,n]

def main():

a = np.array([[12., -3., 3., 15.],

[18., -3., 1., 15.],

[-1., 2., 1., 6.]])

x = GassianEliminationSolver(a)

print(x)

if __name__ == '__main__':

main()

结果:[[12. -3. 3. 15.]

[18. -3. 1. 15.]

[-1. 2. 1. 6.]]

[[12. -3. 3. 15. ]

[ 1.5 1.5 -3.5 -7.5 ]

[-0.08333333 1.75 1.25 7.25 ]]

[1. 2. 3.]

你可能感兴趣的:(高斯消元法python编程)