clear;
clc;

function [T]=genDiagCond(n,k)
    T(1)=1;
    for i=2:n
        T(i)=k^(-1/(n-(i-1)));
    end
    T=diag(T);
endfunction


function [A]=genCond(n,k)
    H=diag(2*ones(n,1))-diag(ones(n-1,1),1)-diag(ones(n-1,1),-1);
    [U,S,V]=svd(H);
    A=U*genDiagCond(n,k)*V';
endfunction

function [b]=getSecondMember(A)
    b=A*ones(size(A,1),1);
endfunction


A=genCond(5,10);
b=getSecondMember(A);


function [L, U, D]=getLUD(A)
    L=tril(A, -1);
    U=triu(A, 1);
    D=diag(diag(A));
endfunction


function [err]=erreurSolution(A, b)
    err=norm(linsolve(A,-b))-norm(ones(size(A,1),1));
endfunction

function [err]=erreurResiduelle(A,b,x)
    err = norm(A*x-b)/norm(b);
endfunction


function [x]=jacobi(A, b, k)
    x=zeros(size(A,1),1);
    [L,U,D] = getLUD(A);
    x=jacobiAux(L, U, D, b, x, k);
endfunction

function [x]=jacobi2(A, b, k)
    x=zeros(size(A,1),1);
    [L,U,D] = getLUD(A);
    x=jacobiAux2(L, U, D, b, x, k);
endfunction

function [x]=jacobiAux2(L, U, D, b, x, k)
    while (~(k == 0 | (erreurResiduelle((L+U+D),b,x) <= 10^(-8))))
        tmp = -inv(D)*(L + U)*x + inv(D)*b;
        x=tmp;
        k=k-1;
    end
endfunction

function [x] = jacobiAux(L, U, D, b, x, k)
    if (~(k == 0 | (erreurResiduelle((L+U+D),b,x) <= 10^(-8)))) then
        x = -inv(D)*(L + U)*x + inv(D)*b;
        x = jacobiAux(L, U, D, b, x, k-1);
    end
endfunction
