2016-04-01 24 views
0

Ich bin derzeit in der Notwendigkeit einer Klasse, die in der Lage sein muss, ein Gleichungssystem wie diese anzuzeigen und zu lösen:Lösen linearer Gleichungen w. drei Variablen numpy

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

ich es eine gute Idee wäre, gedacht, um eine Klasse zu schreiben die linksseitige Dinge des eqation Systems in ein matrixartigen Objekt zu transformieren, hier ist die selbstgemachte-Matrix für dieses System:

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 
:

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

ich das zur Zeit geschrieben habe

Ich suchte ein Modul, um lineare Algebra Pronlems zu lösen, und ich fand numpy. Ich habe im Handbuch gesucht aber nicht ganz meine Lösung gefunden

Wie kann ich das solve funktoin schreiben?

Edit:

Python es wie dieses

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

bearbeiten interprete sollte: Ich habe es mit genau 3 Vars lösen wollen, und als Tupel zurückgeben

Antwort

8

Sie verwenden können 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] 
+0

Kann x in ein Tupel umgewandelt werden? –

+1

Ja sicher, benutze einfach 'tuple (x)' – Zaphod

+0

Danke, das funktioniert! Du hast wirklich meinen Tag gemacht! –

5
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] 
Verwandte Themen