Nugroho's blog.: Manual Gauss Naif Elimination using Python

## Tuesday, April 25, 2017

### Manual Gauss Naif Elimination using Python

How about some manual matrix using manual Gauss just like always, but in Python? Okay, here it is.

I use tuple, I think it's just the same as array for this purpose.

I created matrix a with random value.  It's like linear equation system; three unknown variables with three equation. The purpose of this code is to find x1, x2 and x3.

Oh, in this case, its x0, x1 and x2, :)

Anyway

```

from random import uniform

def showIt(a):
print 'The matrix'
print a[0][0], a[0][1],a[0][2], a[0][3]
print a[1][0], a[1][1],a[1][2], a[1][3]
print a[2][0], a[2][1],a[2][2], a[2][3]
a = []
x = []
for i in range (3):
a.append([])
x.append(0.)
for j in range (4):
a[i].append(uniform(.1,10))

showIt(a)

#manual operation
temp = a[0][0]
a[0][0] /= temp
a[0][1] /= temp
a[0][2] /= temp
a[0][3] /= temp

temp = a[1][0]
a[1][0] = a[1][0]/temp - a[0][0]
a[1][1] = a[1][1]/temp - a[0][1]
a[1][2] = a[1][2]/temp - a[0][2]
a[1][3] = a[1][3]/temp - a[0][3]

temp = a[1][1]
a[1][1] /= temp
a[1][2] /= temp
a[1][3] /= temp

temp = a[2][0]
a[2][0] = a[2][0]/temp - a[0][0]
a[2][1] = a[2][1]/temp - a[0][1]
a[2][2] = a[2][2]/temp - a[0][2]
a[2][3] = a[2][3]/temp - a[0][3]

temp = a[2][1]
a[2][1] = a[2][1]/temp - a[1][1]
a[2][2] = a[2][2]/temp - a[1][2]
a[2][3] = a[2][3]/temp - a[1][3]

temp = a[2][2]
a[2][2] /= temp
a[2][3] /= temp
print ''
print 'Manual Operation Result'
showIt(a)

print ''
print 'back subtitution result'
x[2] = a[2][3]
x[1] = a[1][3]-x[2]*a[1][2]
x[0] = a[0][3]-x[2]*a[0][2]-x[1]*a[0][1]

print x

```

And the result is

```

The matrix
6.93963542354 5.98187429665 5.87719944611 7.80205223834
6.50704604012 8.35799256599 1.97135638303 4.32696464128
5.37640622053 3.00929263631 9.01774536141 4.12795952375

Manual Operation Result
The matrix
1.0 0.861986823739 0.846903199867 1.12427408101
0.0 1.0 -1.28755030345 -1.08720754634
0.0 0.0 1.0 -1.5528377879

back subtitution result
[5.09995513948545, -3.0865643113717116, -1.5528377879039497]
```
.