【问题标题】:Solving linear equations w. three variables using numpy [duplicate]求解线性方程组。使用numpy的三个变量[重复]
【发布时间】:2016-04-01 11:08:41
【问题描述】:

我目前需要一门课,它必须能够显示和求解像这样的方程组:

| 2x-4y+4z=8  |
| 34x+3y-z=30 |
| x+y+z=108   |

我认为编写一个类将方程系统的左侧事物转换为类似矩阵的对象是一个好主意,这是这个系统的自制矩阵:

/2  -4  4\
|34 3  -1|
\1  1   1/

我现在写了这个:

class mymatrix(object):
    def __init__(self):
        o11 = None
        o12 = None
        o12 = None
        o21 = None
        o22 = None
        o23 = None
        o31 = None
        o32 = None
        o33 = None

    def set(row, column, value):
        string = 'o'+str(row)+str(column)+' = '+str(value)
        exec(string)

    def solve(self, listwithrightsidethings):
        #Here I want to solve the system. This code should read  the three    
        #values out of the list and solves the system It should return the
        #values for x, y and z in a tuple: (x, y, z)
        pass

我搜索了一个模块来解决线性代数问题,我发现了 numpy.我在手册中进行了搜索,但没有找到完全解决我的问题的方法

如何编写solve 函数?

编辑:

python 应该这样解释它

/o11, o21, o31\   123
|o21, o22, o32| = 456
\o31, o32, o33/   789

编辑:我想用 3 个变量来解决它,并将它作为 tuple

返回

【问题讨论】:

    标签: python python-3.x numpy linear-algebra equation-solving


    【解决方案1】:

    你可以使用numpy.linalg.solve:

    import numpy as np
    a = np.array([[2, -4, 4], [34, 3, -1], [1, 1, 1]])
    b = np.array([8, 30, 108])
    x = np.linalg.solve(a, b)
    print x # [ -2.17647059  53.54411765  56.63235294]
    

    【讨论】:

    • x可以转换成元组吗?
    • 是的,请使用tuple(x)
    • 谢谢,很好用!你真的让我很开心!
    【解决方案2】:
    import numpy as np
    
    a = np.array([[2, -4, 4], [34, 3, -1], [1, 1, 1]])
    b = np.array([8, 30, 108])
    try:
        x = np.linalg.solve(a, b)
    except LinAlgError:
        x = np.linalg.lstsq(a, b)[0]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多