Function‘round’. Numerical calculation question

17 ビュー (過去 30 日間)
yang li
yang li 2018 年 11 月 17 日
コメント済み: Walter Roberson 2018 年 11 月 17 日
Problem recurrence:
>> round(((6/40000)*10000))
ans =
1
but,
>> round(1.500000000000000)
ans =
2
Why is 1.5 such a value appearing when rounding off?The same value calculation results are different.

回答 (3 件)

Bruno Luong
Bruno Luong 2018 年 11 月 17 日
編集済み: Bruno Luong 2018 年 11 月 17 日
Welcome to the work of floating point arithmetic
>> (6/40000)*10000-1.5
ans =
-2.2204e-16
>>
So actually the calculation of (6/40000)*10000 returns value stricly less than 1.5=3/2. Therefore what you have observed with round is explained.
  2 件のコメント
yang li
yang li 2018 年 11 月 17 日
Thank you for your answer, I need to look at the knowledge of floating point calculations.
Walter Roberson
Walter Roberson 2018 年 11 月 17 日
When you think of 1/10 in binary it can help to think about 1/7 in decimal, in that 1/7 decimal is an infinitely repeating multidigit pattern . If you truncate to any finite number of digits and then multiply back by 7 then you will not get exactly 1. Exactly the same mathematics reasons that lead 1/7 decimal to be infinite lead 1/10 to be infinite repeating multiple digits in binary. It is not a "quality of implementation" issue but rather a fundamental limitation of using any finite number of digits in a "base" numeric representation instead of using rational numbers as the representation .

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


Walter Roberson
Walter Roberson 2018 年 11 月 17 日
1/10 is not exactly representable in binary floating point so you would need to calculate carefully to figure what is being computed.
But algebraically the first of those would be round(2/4) which would be round(0.5) which would round up to 1 and likewise round(1.5) rounds up to 2 so the results you see happen to agree with the algebraic results . Other combinations that are algebraically the same could come out differently because of 1/10 not being exactly representable.
  1 件のコメント
yang li
yang li 2018 年 11 月 17 日
I am sorry that my code part is wrong. The problem is as follows.
>> round((6/40000)*10000)
ans =
1
and
>> round(1.500000000000000)
ans =
2
I use matlab to calculate directly, but the same value gives different results.

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


KSSV
KSSV 2018 年 11 月 17 日
if your number is less than 0.5.._round_ acts like floor function. For number greater than or equla to 0.5 it acts like ceil. YOu may check it yourself. Read about ceil and _floor_
x = 0:0.1:1
floor(x)
ceil(x)
round(x)
  1 件のコメント
yang li
yang li 2018 年 11 月 17 日
I am sorry that my code part is wrong. The problem is as follows.
>> round((6/40000)*10000)
ans =
1
and
>> round(1.500000000000000)
ans =
2
I use matlab to calculate directly, but the same value gives different results.

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

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by