IF statement with multiple logical OR

3 ビュー (過去 30 日間)
George Holt
George Holt 2015 年 12 月 25 日
コメント済み: George Holt 2015 年 12 月 25 日
I'm running a function that solves a given PDE using Euler's method
I attempt to plot the numerical solutions to the PDE at specific times (0.1, 0.5, 1.0 and 2.0) by testing equalities for t in an IF statement
However, only plots for t == 0.1 and t == 0.5 are plotted for some reason
I've tried debugging with breakpoints and the IF statement tests true when t == 0.1 and 0.5, but false when t == 1 and 2, even though the variable t in the workspace == 1 and 2
The relevant code is:
t = 0;
dt = 0.1;
for a = 1 : timesteps
for b = 1 : nodes
u = %solve PDE;
end
t = t + dt;
round(t,1);
if t == 0.1 || t ==0.5 || t == 1.0 || t == 2.0
figure
plot(t,u)
end
end
  2 件のコメント
John D'Errico
John D'Errico 2015 年 12 月 25 日
NEVER test for exact equality of a floating point number. That test will fail most of the time. Note that 0.1 is not representable exactly in a binary arithmetic.
George Holt
George Holt 2015 年 12 月 25 日
Many thanks! I tested for inequalities instead and that works

サインインしてコメントする。

採用された回答

Jan
Jan 2015 年 12 月 25 日
This line does not perform ynathing, because theoutput is not stored:
round(t,1);
You cannot expect, that 0.1+0.1+0.1 is exactly 0.3, because the most decimal floating point values do not have an exact representation in the binary system, such that rounding errors occur.
Better use an arbitrary, but matching threshold:
if any(abs(t - [0.1, 0.5, 1.0. 2.0]) < 1e8)
figure
plot(t,u)
end
Add a meaningful comment to explain the size of the threshold.
Since R2015a:
if ismembertol(t, [0.1, 0.5, 1.0. 2.0])
  1 件のコメント
George Holt
George Holt 2015 年 12 月 25 日
I used
if (0 < t) && (t < 0.2) || (0.4 < t) && (t < 0.6) %etc
but your solution is much nicer!
Thanks

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeBoundary Conditions についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by