Starfruit Python Advanced Lecture 11-Array array (4) Solving linear equations using arrays or matrices (to help you recall linear algebra)

My CSDN blog column: https://blog.csdn.net/yty_7

Github address: https://github.com/yot777/

 

Application background

A group of children and parents went out for a trip. The bus ride was a bus, the child fare was 3 yuan / person, the parent fare was 3.2 yuan / person, and the total fare was 118.4 yuan; the return trip was a train, and the child fare was 3.5 yuan / person, the parent's fare is 3.6 yuan / person, the total fare is 135.2 yuan, ask the number of children and parents respectively.

It is assumed that the number of children is the number of parents.

General formula

 

2. Matrix expression

3. Equation solution (elimination method)

4. Determinant solution

5. Matrix solution

6. Use matrix solution to write programs to solve linear equations

(1) Array array solution

import numpy as np

#数组array解法
print("数组array解法:")
A1 = np.array([[3 , 3.2],[3.5, 3.6]])
b1 = np.array([118.4, 135.2])

#数组array求逆矩阵
A1_1 = np.linalg.inv(A1)
print("A=\n", A1)
print("A_1=\n", A1_1)
print("b=", b1)

#数组array求解公式
x1 = np.dot(A1_1,b1)
print("方程最终的解x=\n",x1)

The running result is:

数组array解法:
A=
 [[3.  3.2]
 [3.5 3.6]]
A_1=
 [[-9.    8.  ]
 [ 8.75 -7.5 ]]
b= [118.4 135.2]
方程最终的解x=
 [16. 22.]

(2) Matrix solution

import numpy as np

#矩阵matrix解法
print("\n矩阵matrix解法:")
A2 = np.mat([[3 , 3.2],[3.5, 3.6]])
b2 = np.mat([118.4, 135.2])

#矩阵matrix求逆矩阵
A2_1 = A2.I
print("A=\n", A2)
print("A_1=\n", A2_1)
print("b=", b2)

#矩阵matrix求解公式
#注意矩阵乘法要严格按照(2,2)*(2,1)的形状才能进行,因此要把b2转置
x2 = A2_1 * b2.T
print("方程最终的解x=\n",x2)

The running result is:

矩阵matrix解法:
A=
 [[3.  3.2]
 [3.5 3.6]]
A_1=
 [[-9.    8.  ]
 [ 8.75 -7.5 ]]
b= [[118.4 135.2]]
方程最终的解x=
 [[16.]
 [22.]]

to sum up

Solving linear equations in one variable using Python, the most important is the formula:

Convert to Python program

You can use array array or matrix matrix . Please pay attention to the difference between inverse matrix and multiplication .

 

My CSDN blog column: https://blog.csdn.net/yty_7

Github address: https://github.com/yot777/

If you think this chapter is helpful to you, welcome to follow, comment and like! Github welcomes your Follow and Star!

Published 55 original articles · won praise 16 · views 6111

Guess you like

Origin blog.csdn.net/yty_7/article/details/104599004