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 iteracionesEl error de la aprox. a ln(2) fue 0.1La aprox. a ln(2) fue 0.64563Se realizaron 3 iteracionesEl error de la aprox. a ln(1.5) fue 0.041667La 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