MATLAB: Ignoring IF statements error

comparisonconditionalerrorif

I'm having a problem with Matlab and its interpretation of the operator "<" Here's my code:
function logo()
suma=0;
suma2=0;
k=0;
k2=0;
error=1;
error2=1;
while 1
k=k+1;
if error>=0.10
valor=suma;
suma = suma + ((-1)^(k+1)/k);
error = abs(suma-valor);
end
if error<0.10
break;
end
end
while 1
k2=k2+1;
if error2>=0.10
valor2=suma2;
suma2= suma2 + (((-1)^(k2+1))*((0.5)^k2))/k2;
error2 = abs(suma2-valor2);
end
if error2<0.10
break;
end
end
format long
fprintf("\nSe realizaron " + k + " iteraciones")
fprintf("\nEl error de la aprox. a ln(2) fue " + error)
fprintf("\nLa aprox. a ln(2) fue " + suma + "\n")
fprintf("\nSe realizaron " + k2 + " iteraciones")
fprintf("\nEl error de la aprox. a ln(1.5) fue " + error2)
fprintf("\nLa aprox. a ln(1.5) fue " + suma2)
end
It's kind of simple, I'm stating an equation inside a loop, which is going to continue repeating itself until the "error" value is less than 0.10… The problem is that I'm getting results of
Se realizaron 10 iteraciones
El error de la aprox. a ln(2) fue 0.1
La aprox. a ln(2) fue 0.64563
Se realizaron 3 iteraciones
El error de la aprox. a ln(1.5) fue 0.041667
La aprox. a ln(1.5) fue 0.41667>>
It doesn't have any sense to me, because I'm getting error=0.1, so the code just broke the loop before the error<0.1 and I don't know why, I even tried to state something like
if error<0.1 && error~=0.1
break;
end
but I'm still getting an error=0.1

Best Answer

I do not see any problem in your code. It does exactly, what is expected. Here a brushed up version:
suma1 = 0;
suma2 = 0;
k1 = 0;
k2 = 0;
error1 = 1;
error2 = 1;
while 1 % Or better: while error1 >= 0.1
k1 = k1+1;
valor = suma1;
suma1 = suma1 + (-1)^(k1+1) / k1;
error1 = abs(suma1 - valor);
if error1 < 0.10
break;
end
end
while 1
k2 = k2+1;
valor2 = suma2;
suma2 = suma2 + (-1)^(k2+1) * 0.5^k2 / k2;
error2 = abs(suma2 - valor2);
if error2 < 0.10
break;
end
end
fprintf('error1: %.16g\n', error1);
fprintf('error2: %.16g\n', error2);
Note that this replies 0.09999999999999998 for error1, which is displayed as 0.1 in the command window with format long. But you can check the value easily:
error1 - 0.1
and see the difference of -2.776e-17. This means that the < operator works as expected.
Related Question