from __future__ import division
from numpy import mat
#Gauss Jacobi
A = mat([[ 2, 1 , 1] ,[3, 5, 2],[2, 1, 4]])
B = mat([[ 5],[ 15],[ 8]])
x1old = 0 ;x2old = 0 ; x3old = 0 #intial assumption of x1,x2 & x3
print 'x1 = (5 - x2 - x3)/2 '
print 'x2 = (15 - 3x1 - 2x3)/5 '
print 'x3 = (8 - 2x1 - x2)/4'
for i in range(1,5):
print '\n Iteration Number : %d\n'%(i)
x1 = (5 - x2old - x3old)/2 #
x2 = (15 - 3*x1old - 2*x3old)/5 #
x3 = (8 - 2*x1old - x2old)/4 #
print ' \n x1 = %f\n x2 = %f\n x3 = %f\n'%(x1,x2,x3)
x1old = x1#
x2old = x2#
x3old = x3#
from __future__ import division
from numpy import mat
#Gauss Seidel
A = mat([[ 2, 1 , 1] ,[3, 5, 2],[2, 1, 4]])
B = mat([[ 5],[ 15],[ 8]])
x1old = 0 ;x2old = 0 ; x3old = 0 #intial assumption
print '(x1 = 5 - x2 - x3)/2 '
print '(x2 = 15 - 3x1 - 2x3)/5 '
print '(x3 = 8 - 2x1 - x2)/4'
for i in range(1,3):
print '\n Iteration Number : %d'%(i)
x1 = (5 - x2old - x3old)/2 #
x1old = x1#
x2 = (15 - 3*x1old - 2*x3old)/5 #
x2old = x2#
x3 = (8 - 2*x1old - x2old)/4 #
x3old = x3#
print ' \n x1 = %f\n x2 = %f\n x3 = %f\n'%(x1,x2,x3)
from __future__ import division
from numpy import array,zeros,ones,nditer,vstack,hstack
#Gauss Seidel
A = array([[ 3, 1],[ 1 ,-3]])
B = array([[ 5],[5 ]])
X=zeros([6,2])
print ('Using a matrix to display the results after each iteration, first row represents initial assumption')
X[0,0] = 0; X[0,1] = 0 ;#initial assumption
maxit = 1000;#Maximum number of iterations
err = 0.0003 ;
print('x1 = (5-x2)/3');
print('x2 = (x1 - 5)/3');
for i in range(1,maxit):
X[i,0] = (5 - X[i-1,1])/3 ;
X[i,1] = (X[i,0] - 5)/3 ;
#Error Calculations
err1 =abs((X[i,0] - X[i-1,0])/X[i,0])
err2 =abs((X[i,1]- X[i-1,1])/X[i,1])
#Terminating Condition
if err >= err1 and err >= err2:
print 'The system converges to the solution ( %f , %f ) in %d iterations\n'%(X[i,0],X[i,1],i-1)
break
#calcution of true error i.e. difference between final result and results from each iteration
trueerr1 = abs(X[:,0] - X[i,0]*ones([i+1,1])) ;
trueerr2 = abs(X[:,1] - X[i,1]*ones([i+1,1])) ;
#displaying final results
print 'Final Result is as : '
for i in range(0,5):
print '%.10f'%X[i,:][1],'\t%.10f'%X[i,:][0],'\t%.10f'%trueerr1[0,i],'\t',trueerr2[0,i]
from numpy import mat
#Gauss Seidel
A = mat([[ 1, -3],[3, 1 ]])
B = mat([[ 5],[5] ])
x1old = 0 #intial assumption
x2old = 0 #intial assumption
print 'x1 = 5 + 3*x2 '
print 'x2 = 5 - 3*x1 '
for i in range(1,4):
x1 = 5 + 3*x2old
x1old = x1
x2 = 5 - 3*x1old
x2old = x2
print '\n Iteration : %d x1 = %d and x2 = %d\n'%(i,x1,x2)
print 'It is clear that the process do not converge towards the solution, rather it diverges.'