I have a loop with the following code But when a=3.000 and b=3 the result is B not A. (this code not the actual code just an illustration)
if a>=b
disp(A)
else
disp(B)
end

1 件のコメント

jonas
jonas 2018 年 7 月 10 日
編集済み: jonas 2018 年 7 月 10 日
Difficult to tell from the limited information, but I would imagine it has to do with floating point numbers. Also, in your example, the output is actually A.

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

 採用された回答

Jan
Jan 2018 年 7 月 10 日
編集済み: Jan 2018 年 7 月 10 日

0 投票

Remember, that Matlab works with the type double, which is a floating point type according to IEEE754. If you define a variable as:
a = 2.99999999999999
if is displayed as 3.000, when the format in the output to the command window is set to 'shortE'.
doc format
Try this:
disp(a - b)
fprintf('%.16g\n', a)
fprintf('%.16g\n', b)
You will see, that Matlab works correctly, but only the rounded output to the command window is confusing.
See also: FAQ: Why is 0.1+0.2 ~= 0.3? and hundreds of other related threads - search e.g. for "IEEE754" or "floating point" in this forum. The tag "faq6.1" is used frequently also for this kind of problems.

2 件のコメント

yulia kurniasih
yulia kurniasih 2018 年 7 月 12 日
so there is nothing I can do to solve it?
Jan
Jan 2018 年 7 月 12 日
The explanations mean, that there is not a problem, so there cannot be a solution. The comparison |a>=b| is performed correctly, so what do you want to change?

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

その他の回答 (0 件)

カテゴリ

質問済み:

2018 年 7 月 10 日

コメント済み:

Jan
2018 年 7 月 12 日

Community Treasure Hunt

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

Start Hunting!

Translated by