numpy 解一道简单数学题

题目

A group took a trip on a bus, at 3 per child and 3.20 per adult for a total of 118.40.

They took the train back at 3.50 per child and 3.60 per adult for a total of 135.20.

How many children, and how many adults?

求解过程

设有x1个children,x2个adults,线性方程组为:

\[3x_1+3.2x_2 = 118.4 \]

\[3.5x_1+3.6x_2 = 135.2 \]

矩阵形式表示为:

\[\begin{bmatrix} 3 & 3.2 \\ 3.5 & 3.6 \end{bmatrix} \begin{bmatrix} x_1 \\ x_2 \\ \end{bmatrix} = \begin{bmatrix} 118.4 \\ 135.2 \end{bmatrix} \]

化为:

\[\begin{bmatrix} x_1 \\ x_2 \end{bmatrix} = { \begin{bmatrix} 3 & 3.2 \\ 3.5 & 3.6 \end{bmatrix} }^{-1} \begin{bmatrix} 118.4 \\ 135.2 \end{bmatrix} \]

接下来就是使用numpy求解了

代码

import numpy as np


a = np.matrix('3. 3.2;3.5,3.6')
b = np.matrix('118.4;135.2')

inverse_a = np.linalg.inv(a)
print(inverse_a)

result = inverse_a * b
print(result)

结果

\[inverse\_a = \begin{bmatrix} -9 & 8 \\ 8.75 & -7.5 \end{bmatrix} \]

\[result = \begin{bmatrix} 16 \\ 22 \end{bmatrix} \]

也就是说是16个children,22个adults

posted @ 2017-04-11 16:41  Weyne  阅读(175)  评论(0编辑  收藏