Solving linear equations w. three variables using numpy

h_e_u_r_e_k_a picture h_e_u_r_e_k_a · Apr 1, 2016 · Viewed 10.8k times · Source

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/

I have written this currently:

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

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

How can I write the solve functoin?

Edit:

python should interprete it like this

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

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

Answer

zaphodef picture zaphodef · Apr 1, 2016

You can use 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]