Getting wrong results while calling a function.

7 ビュー (過去 30 日間)
Asif Rahman
Asif Rahman 2021 年 9 月 2 日
コメント済み: Rik 2021 年 9 月 3 日
I have written a simple function. It takes two inputs, only when two inputs are equal the output should be zero.
function I = getI(E,Eg)
if (E<=1.5) && (E ~= Eg)
I=(500*E)/1.5;
elseif (E>1.5) && (E<=4) && (E ~= Eg)
I=500*(1-((E-1.5)/(4-1.5)));
elseif (E==Eg)
I=0;
end
end
Now the function works as expected most of times,but when the value of Eg is 1.38,1.39,1.4, 2.84 or 2.6 the code doesnot gives I=0 even when the value of Eg is equal to E. Example:
I tried changing the if conditions, changing their positions. No change.

回答 (1 件)

Rik
Rik 2021 年 9 月 2 日
Some numbers cannot be represented exactly in binary. You will either need to round both numbers to make sure they have the exact same representation, or compare the differences to a tolerance.
  2 件のコメント
Asif Rahman
Asif Rahman 2021 年 9 月 2 日
Shouldn't this show wrong result also?
If not than can you please guide me about a different approach. Thanks.
Rik
Rik 2021 年 9 月 3 日
This shows the correct result, because the numbers are generated the same way.
If a number can't be represented exactly by a double, it might be represented slightly differently if the method of calculation is different, e.g. writing 1.4 directly and using the colon operator.

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

カテゴリ

Help Center および File ExchangeEEG/MEG/ECoG についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by