- 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?
조회 수: 3 (최근 30일)
이전 댓글 표시
Muhammad Hassaan Bin Tariq
2022년 10월 18일
댓글: Muhammad Hassaan Bin Tariq
2022년 10월 18일
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
Stephen23
2022년 10월 18일
"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.
채택된 답변
Tobias Panitz
2022년 10월 18일
Hey,
have you tried using the modulus function?
if mod(cycles,0.5) == 0
continue;
end
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!