Gauss- Seidel Error tolerance

46 ビュー (過去 30 日間)
Muhammad Mubinur Rahman
Muhammad Mubinur Rahman 2021 年 9 月 10 日
編集済み: Abolfazl Chaman Motlagh 2021 年 9 月 11 日
I am using this code below to implement gauss-seidel method equation solving. I did set a maximum error value i.e tol in my code. The code should run as long as current error is greater than maximum error. However for tol = 10^-5 , A = [8 -3 2; 4 11 -1; 6 3 12] and b = [20;33;35], the while loop breaks even when the condition is still not brached i.e current error is still greater than tol. Why is this happening so? It makes sense if I consider first 5 decimal points but I do not intend to limit it to five decimal points only.
function [X,err] = gauss_seidel(A,b)
tol = 10^-05;
[M,N] = size(A);
if(M~=N)
error('Error');
end
for i=1:M
row = abs(A(i,:));
d = sum(row) - row(i);
if d>=row(i)
error("Given matrix is not diagonally dominant");
end
end
itr = 0;
X = zeros(M,1);
err = inf;
while err>tol
Xold = X;
for i = 1:M
total = 0;
for j = 1:i-1
total = total + A(i,j)*X(j);
end
for j = i+1 : N
total = total + A(i,j)*Xold(j);
end
X(i) = (1/A(i,i)) * (b(i)-total);
end
itr = itr+1;
err = abs(Xold-X);
end
fprintf("%.10f ",tol);
fprintf("%.10f",err);
fprintf("Method converges in %d iteration\n",itr);
end

回答 (1 件)

Abolfazl Chaman Motlagh
Abolfazl Chaman Motlagh 2021 年 9 月 11 日
編集済み: Abolfazl Chaman Motlagh 2021 年 9 月 11 日
you have an unclear statement in while.after first iteration the err is 3x1 vector and tol is a scalar.
change the statement to a norm of vector err. for example inf-norm:
while max(err)>tol
...
end

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by