#!/usr/bin/python
# -*- coding: utf-8 -*-

from mls import *

n=input('Order Matrix A'+'\n'+'n=')
r=range(n)

def d(i,j):
    if i==j: return 1
    else: return 0

A=M([[0 for i in r] for i in r])
B=M([[0 for i in r]])
D=M([[0 for i in r] for i in r])
E=M([[d(i,j) for i in r] for j in r])
for i in r:
    for j in r:
        s='A'+str(i+1)+str(j+1)+'='
        A[j][i]=input(s)
        if i==j: D[i][j]=A[i][j]
    s='B'+str(i+1)+'='
    B[0][i]=input(s)
print 'To apply simple iteration method'
print 'original system AX=B must be' 
print 'converted to form x=ax+b ,'
print 'where ||a||<1'
print
a,b=E-inv(D)*A,inv(D)*B
q=float(norm(a))
print 'a=',a
print 'b=',b
print
s=''
for i in r:
    if i==0:s+='|x'+str(i+1)+'| = | ' 
    else: s+='|x'+str(i+1)+'|   | '
    for j in r:
        if a[j][i]>=0:s+="%.5f"%a[j][i]+'   '
        else:s+="%.4f"%a[j][i]+'   '
    if b[0][i]>=0:t=5
    else:t=4   
    if i==0:s+='||x'+str(i+1)+'| + |'+"%.*f"%(t,b[0][i])+'|'
    else: s+='||x'+str(i+1)+'|   |'+"%.*f"%(t,b[0][i])+'|'
    print s
    s=''
print
print '||a||=',q
print
if q>=1: print 'Iterations cancel'
else:
    x1,i=b,1
    while True:
        x2=a*x1+b
        e=norm(x2-x1)
        print 'Iteration',i
        for l in r:
            print 'x'+str(l+1),'=',round(x2[0][l],5)
        print 'absolute error ',q*e/(1-q)
        print
        j=input( 'To continue type 1\n\
To exit type 0\n')
        if j==1:
             x1=x2
             i+=1
        if j==0: break



