- 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 回表示 (過去 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!