求解线性方程组w.使用numpy的三个变量 [英] Solving linear equations w. three variables using numpy

查看:89
本文介绍了求解线性方程组w.使用numpy的三个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm currently in need of a class, which must be able to display and solve an equation system like this one:

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

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

I thought it would be a good idea to write a class to transform the left-side things of the eqation system into a matrix-like object, here is the self-made-matrix for this system:

/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.我已经在手册中搜索过,但是找不到解决我问题的方法

I searched a module to solve linear algebra pronlems, and I found numpy. I've searched in the manual but didn't find quite my solution of my problem

我怎么写solve functoin?

How can I write the solve functoin?

python应该这样解释

python should interprete it like this

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

我想用3个变量解决它,并以元组

I want to solve it w exactly 3 vars, and return it as a tuple

推荐答案

您可以使用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]

这篇关于求解线性方程组w.使用numpy的三个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆