Ignoring IF statements error
Mostrar comentarios más antiguos
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
3 comentarios
Is that MATLAB code?:
fprintf("\nSe realizaron " + k + " iteraciones")
Also note that shadowing the inbuilt error function is a very bad idea.
@Stephen: It works with modern the string class:
s1 = string('\nSe realizaron ');
s2 = string(' iteraciones');
fprintf(s1 + 10 + s2)
>> Se realizaron 10 iteraciones
I do not have R2017a, where the creation of the string class seems to work with "...", but in R2016b the string() command might be equivalent.
Stephen23
el 21 de Ag. de 2017
@Jan Simon: thank you for the explanation.
Respuesta aceptada
Más respuestas (0)
Categorías
Más información sobre Surrogate Optimization en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!