Gauss- Seidel Error tolerance

16 次查看(过去 30 天)
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
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 CenterFile Exchange 中查找有关 Mathematics and Optimization 的更多信息

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by