Gaussian Elimination

  • warning: realpath() [function.realpath]: SAFE MODE Restriction in effect. The script whose uid is 1005 is not allowed to access /tmp owned by uid 0 in /var/www/sites/sugree/codenone.com/subdomains/www/html/includes/file.inc on line 190.
  • warning: realpath() [function.realpath]: SAFE MODE Restriction in effect. The script whose uid is 1005 is not allowed to access /tmp owned by uid 0 in /var/www/sites/sugree/codenone.com/subdomains/www/html/includes/file.inc on line 190.
class Matrix:
    def __init__(self,m,n,data=None):
        self.m = m
        self.n = n
        self.data = data or [[0]*n]*m
 
    def get(self,i,j):
        return self.data[i][j]
 
    def set(self,i,j,v):
        self.data[i][j] = v
 
    def swap_row(self,i,j):
        """swap row i and j"""
        self.data[i],self.data[j] = self.data[j],self.data[i]
 
    def map_row(self,func,i):
        """evaluate `func` on the row i"""
        self.data[i] = map(func,enumerate(self.data[i]))
 
    def show(self,label=''):
        if label:
            print label
        for l in self.data:
            for x in l:
                print '%6.3f' % x,
            print
 
class Solver:
    def solve(self):
        pass
 
    def find_pivot(self,i,j):
        """find pivot in column j, starting in row i"""
        max_val = self.get(i,j)
        max_ind = i
        for k in range(i+1,self.m):
            val = self.get(k,j)
            if abs(val) > abs(max_val):
                max_val = val
                max_ind = k
        return max_val,max_ind
 
    def divide_row(self,i,v):
        """divide row i by v"""
        self.map_row(lambda x: x[1]/v,i)
 
    def substract_row(self,i,j):
        """substract all rows by row i column j"""
        for u in range(self.m):
            if u != i:
                self.map_row(lambda x: x[1]-(self.get(u,j)*self.get(i,x[0])),u)
 
class GaussianElimination(Matrix,Solver):
    def __init__(self,data):
        m = len(data)
        n = len(data[0])
        Matrix.__init__(self,m,n,data)
 
    def solve(self):
        i,j = 0,0
        while i < self.m and j < self.n:
            max_val,max_ind = self.find_pivot(i,j)
            if max_val != 0:
                self.swap_row(i,max_ind)
                self.divide_row(i,max_val)
                self.substract_row(i,j)
                i += 1
            j += 1
        return [self.get(i,-1) for i in range(self.m)]
 
ms = []
ms += [[[8,7.4,8.225342],
        [7.4,8.72,10.731329]]]
ms += [[[2,1,-1,8],
        [-3,-1,2,-11],
        [-2,1,2,-3]]]
for mi in ms:
    m = GaussianElimination(mi)
    m.show('problem')
    print m.solve()

ย้าย Codenone

ประกาศย้าย Codenone ไปใช้ Forum ของ Blognone แทนครับ ตามไปตั้งกระทู้ต่อได้ที่ Codenone Forum (รายละเอียดอ่านจากกระทู้ ย้าย Codenone ไปรวมกับ Blognone)

กระทู้เก่าๆ จะย้ายตามไปในภายหลัง ตอนนี้ปิดการโพสต์กระทู้ไว้ เหลือไว้เฉพาะอ้างอิงเท่านั้น