My if x ~= y statement is not working

2 ビュー (過去 30 日間)
Nils Norlander
Nils Norlander 2017 年 3 月 2 日
コメント済み: dpb 2017 年 3 月 2 日
Dear all,
I have a really simple annoying problem which I can't wrap my head around.
In my code:
for k = time
if E_load2(k) ~= Allowed_winter
disp(k)
overload = overload+1;
else
overload = overload+0;
end
end
I can see that the if loop returns the logical true even though I know that E_load2(k) == to Allowed_winter at that the certain k, and thus "overload" becomes larger than it should.
Allowed_winter = -0.5 if that helps.
Please help!

採用された回答

dpb
dpb 2017 年 3 月 2 日
== is precisely that to the LSB; undoubtedly the values in E_load2 in question are close but not identically equal. See the <FAQ> for the "why" in some detail.
For the k in question try
delt=E_load2-Allowed_winter
and observe the result; you'll find it will be something very small but not zero.
Use a tolerance on the comparison or later releases have the function ismembertol that makes writing the expression a little easier.
overload=sum(~ismembertol(E_load2,Allowed_winter));
should do the trick (note no loop needed here).
  6 件のコメント
Nils Norlander
Nils Norlander 2017 年 3 月 2 日
Sorry, I'm pretty new to this community as I learned Matlab for my masters thesis.
dpb
dpb 2017 年 3 月 2 日
No problem; just wondered about the inconsistency if ismembertol did work out (as I figured it would)...

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

その他の回答 (2 件)

Adam
Adam 2017 年 3 月 2 日
編集済み: Adam 2017 年 3 月 2 日
Never compare floating point numbers with == or ~=
Floats are not 100% accurate so you will run into these kinds of confusions. If you get a value that is 0.50000000000001 then it will return false even though it may have been the result of a floating point rounding error.
  1 件のコメント
Nils Norlander
Nils Norlander 2017 年 3 月 2 日
Thank you so much! You've saved me a lot of head ache.

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


John D'Errico
John D'Errico 2017 年 3 月 2 日
Why are you bothering with this line?
overload = overload+0;
The last time I checked, adding zero to something does nothing but waste CPU cycles. I sincerely doubt that your goal is code that runs more slowly than necessary.
Anyway, it is high time to learn how to use MATLAB.
overload = sum(E_Load2 ~= Allowed_winter);
No loop required.
Or, if time is just the indices of a subset of the elements of E_load2, then use
overload = sum(E_Load2(time) ~= Allowed_winter);
Finally, your problem with the test. This is likely due to the fact that E_load2 or Allowed_winter is not exactly -0.5 in some cases.
  1 件のコメント
Nils Norlander
Nils Norlander 2017 年 3 月 2 日
Thank you for your input! I knew the overload = overload+0; was unnecessary, and was simply there in a desperate way to bugtest

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

カテゴリ

Help Center および File ExchangeGet Started with MuPAD についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by