- work with integers, or
- use tolerances when comparing (i.e. do not use exact equality), avoid FIX, etc.
Why loop is not being excluded with the given condition?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Muhammad Hassaan Bin Tariq
el 18 de Oct. de 2022
Comentada: Muhammad Hassaan Bin Tariq
el 18 de Oct. de 2022
I am using the continue function to exclude the nodes of a sine function in matlab. When I start from 0, it is excluding all the nodes. However, when I start from 0.1 (for some reasons), it does not exclude the nodes i.e. 1.5, 2.5, 3, 3.5. Can you tell me what can be the reason and how to deal with it?
F_b = 16000; % N
A_b = 125.66; % mm^2
for cycles = 0:0.1:10
if cycles/0.5 == fix(cycles/0.5)
continue
end
disp(cycles)
end
The other is
F_b = 16000; % N
A_b = 125.66; % mm^2
for cycles = 0.1:0.1:10
if cycles/0.5 == fix(cycles/0.5)
continue
end
disp(cycles)
end
Thanks for the help in advance.
Regards,
Muhammad Hassaan Bin Tariq
2 comentarios
Stephen23
el 18 de Oct. de 2022
"Can you tell me what can be the reason..."
Because 0.1 cannot be exactly stored in a binary floating point number (in exactly the same way that you cannot write 1/3 exactly on a piece of paper using a decimal fraction). The floating point error accumulates differently in the COLON operator, depending on the provided values. Lets compare:
cycles0 = 0:0.1:10;
cycles1 = 0.1:0.1:10;
fprintf('%.40f\n', cycles0(16)/0.5, fix(cycles0(16)/0.5), cycles1(15)/0.5, fix(cycles1(15)/0.5))
"...and how to deal with it?"
Either:
Your current approach is numerically fragile and should be avoided.
Respuesta aceptada
Tobias Panitz
el 18 de Oct. de 2022
Hey,
have you tried using the modulus function?
if mod(cycles,0.5) == 0
continue;
end
0 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!