MATLAB: Sum that should add up to 0 is giving wrong result. Why is this happening

for loopsum

Here is the code I used. I tried the built-in function too and it is giving me the same wrong result "-5.3291e-15".
x = (-10:.1:10);
sum=0;
for i=1:201
sum1=sum;
sum=sum+x(i);
X=[num2str(sum1),'+',num2str(x(i)),'=',num2str(sum)];
display(X)
end

Best Answer

Welcome to the world of numerics with limited precision. The result is not "wrong", but exactly what is expected. See https://www.mathworks.com/matlabcentral/answers/57444-faq-why-is-0-3-0-2-0-1-not-equal-to-zero:
0.1 + 0.1 + 0.1 - 0.3
This does not produce 0.0 and this is not a bug, but the known effect of converting decimal numbers to the internally used binary representation according to the IEEE754 standard (use this term to search in the internet). Most decimal numbers do not have an exact binary representation using a limited number of digits. Then the conversion must include a rounding, which leads to the effect you observe. Maybe it is easier to see with integer values:
The type double uses about 16 digits in Matlab, all other programming languages and internally in all modern processors. Then 1e17 + 1 cannot be distinguished from 1e7:
(1e17 + 1) - 1e17
This is not 1 but 0.
By the way: Using "sum" as a variable causes troubles frequently, if the user tries to call the built-in function afterwards:
clear('sum'); % Just to be sure
sum(1:10) % "1:10" is the input argument of the function SUM
sum = rand(1, 10); % "sum" becomes a variable
sum(1:10) % Now "1:10" is the index!
This is confusing, most of all if it appears in scripts. The general rule is: Do not shadow built-in function.