美文网首页
python解决线性代数

python解决线性代数

作者: Python_Camp | 来源:发表于2022-05-08 20:15 被阅读0次

    假设你有一个鸡、犀牛和山羊的动物园。如果有12个头,38只脚和10只角,每种动物有多少只?解决这个问题的一个方法是将每个属性的方程式转化为矩阵。

    低阶问题初探:

    回顾题目:现有一笼子,里面有鸡和兔子若干只,数一数,共有头14个,腿38条,球鸡和兔子各有多少只?

    假设有x只鸡,y只兔子

    x + y = 14
    2x + 4y = 38

    参考一个代码

    import matplotlib.pyplot as plt
    import numpy as np
    from mpl_toolkits.mplot3d import Axes3D
    import scipy as sp
    import scipy.linalg
    import sympy as sy
    sy.init_printing() 
    np.set_printoptions(precision=3)
    np.set_printoptions(suppress=True)
    
    x = np.linspace(-5, 5, 100)
    y1 = -x + 14
    y2 = -0.5*x + 19*0.5
    
    fig, ax = plt.subplots(figsize = (12, 7))
    ax.scatter(9, 5, s = 200, zorder=5, color = 'r', alpha = .8) 
    ax.plot(x, y1, lw =3, label = '$x+y=14$')
    ax.plot(x, y2, lw =3, label = '$2x+4y=38$')
    ax.plot([1, 1], [0, 5], ls = '--', color = 'b', alpha = .5)
    ax.plot([-5, 1], [5, 5], ls = '--', color = 'b', alpha = .5)
    ax.set_xlim([-5, 5])
    ax.set_ylim([0, 12])
    
    ax.legend()
    s = '$(1,5)$'
    ax.text(9, 5.5, s, fontsize = 20)
    ax.set_title('Solution of $x+y=14$, $2x+4y=38$', size = 22)
    ax.grid()
    
    image.png
    x, y = [-1, 0, 1], [-1, 0, 1]
    X, Y = np.meshgrid(x, y)
    fig, ax = plt.subplots(figsize = (12, 7))
    ax.scatter(X, Y, s = 200, color = 'red')
    ax.axis([-2, 3.01, -2.01, 2])
    ax.spines['left'].set_position('zero') # alternative position is 'center'
    ax.spines['right'].set_color('none')
    ax.spines['bottom'].set_position('zero')
    ax.spines['top'].set_color('none')
    ax.grid()
    plt.show()
    
    image.png

    3个未知数和3个方程式

    x + y + z = 12

    2x + 4y + 4*z = 38

    0x + 1y + 2*z = 10

    import numpy as np
    import matplotlib as plt
    import matplotlib.pyplot as plt
    
    
    '''
    x + y + z = 12
    2*x + 4*y + 4*z = 38
    0*x + 1*y + 2*z = 10
    '''
    
    x1 = np.linspace(0, 35, 20)
    x2 = np.linspace(0, 20, 20)
    X1, X2 = np.meshgrid(x1, x2)
    
    fig = plt.figure(figsize = (9, 9))
    ax = fig.add_subplot(111, projection = '3d')
    
    X3 = 12 - X2 - X1
    ax.plot_surface(X1, X2, X3, cmap ='winter', alpha = 1) 
    
    X3 = 19*0.5 - X2 - 0.5*X1
    ax.plot_surface(X1, X2, X3, cmap ='summer', alpha = 1)
    
    X3 = 5 - 0.5*X2
    ax.plot_surface(X1, X2, X3, cmap ='spring', alpha = 1)
    
    #numpy 求解交点
    A = np.array([[1,1,1],[2,4,4],[0,1,2]])
    B = np.array([12,38,10])
    dot = np.linalg.solve(A,B)
    
    x,y,z = [int(i) for i in dot]
    print(x,y,z)
    #ax.scatter(29, 16, 3, s = 200, color = 'black')
    ax.scatter(x, 0, 0, s = 200, color = 'black')
    ax.scatter(0, y, 0, s = 200, color = 'black')
    ax.scatter(0, 0, z, s = 200, color = 'black')
    plt.show()
    
    image.png

    求解结果:5,4 ,3

    5只鸡
    4只犀牛
    3只羊

    相关文章

      网友评论

          本文标题:python解决线性代数

          本文链接:https://www.haomeiwen.com/subject/jzwqurtx.html