forked from JanisErdmanis/PythonPhysics
-
Notifications
You must be signed in to change notification settings - Fork 0
/
6.1.py
50 lines (39 loc) · 962 Bytes
/
6.1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 8 18:08:55 2013
@author: akels
"""
from __future__ import division, print_function
from numpy import array,empty
A = array([[ 4,-1,-1,-1 ],
[ -1,0,3,0 ],
[ -1,3,0,-1 ],
[ -1,-1,0,4]], float)
v = array([ 5, 5, 0, 0 ],float)
N = len(v)
# Gaussian elimination
for m in range(N):
# Divide by the diagonal element
div = A[m,m]
A[m,:] /= div
v[m] /= div
# Now subtract from the lower rows
for i in range(m+1,N):
mult = A[i,m]
A[i,:] -= mult*A[m,:]
v[i] -= mult*v[m]
# Backsubstitution
x = empty(N,float)
for m in range(N-1,-1,-1):
x[m] = v[m]
for i in range(m+1,N):
x[m] -= A[m,i]*x[i]
print(x)
### Checking if correct
from numpy.linalg import solve
A = array([[ 4,-1,-1,-1 ],
[ -1,0,3,0 ],
[ -1,3,0,-1 ],
[ -1,-1,0,4]], float)
v = array([ 5, 5, 0, 0 ],float)
print(solve(A,v))