Unexpected floor() function result?

12 ビュー (過去 30 日間)
Albert Hsueh
Albert Hsueh 2021 年 5 月 17 日
編集済み: Adam Danz 2021 年 5 月 17 日
>> (1.2-floor(1.2))*10
ans =
2.0000
>> floor((1.2-floor(1.2))*10)
ans =
1
Have I misunderstood how the floor function interacts with other math operations?
  2 件のコメント
Albert Hsueh
Albert Hsueh 2021 年 5 月 17 日
>> ((1.2-floor(1.2))*10) == 2
ans =
logical 0
Albert Hsueh
Albert Hsueh 2021 年 5 月 17 日
I'm guessing this is some really small numerical inpercision in the back end. The following results in the expected result
>> round((1.2-floor(1.2))*10)==2
ans =
logical 1

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

採用された回答

Adam Danz
Adam Danz 2021 年 5 月 17 日
編集済み: Adam Danz 2021 年 5 月 17 日
This is round-off error and is caused by limitation to representing floating point decimals.
1.2-floor(1.2)
ans = 0.2000
1.2-floor(1.2) - 0.2000 % Reveal round-off error
ans = -5.5511e-17
Likewise,
(1.2-floor(1.2))*10
ans = 2.0000
(1.2-floor(1.2))*10 - 2.000 % Reveal round-off error
ans = -4.4409e-16
Here's another example,
4/3
ans = 1.3333
4/3-1
ans = 0.3333
(4/3 - 1)*3
ans = 1.0000
(4/3 - 1)*3 - 1 % Reveal round-off error
ans = -2.2204e-16
See this answer for a list of references to learn more about round-off error and floating point representation. If there's a specific issue you need to solve to avoid the problem, add some details and I may be able to point you in the right direction.

その他の回答 (0 件)

カテゴリ

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

タグ

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by