I have a variable whose value i am approximating to the nearest integer by using round function. But even when value of the variable becomes 0.5, the round function returns 0.

2 ビュー (過去 30 日間)
shan=dy/d;
disy=round(shan);
Even when the value of shan becomes 0.5, the value of disy remains zero
  2 件のコメント
Roger Stafford
Roger Stafford 2016 年 6 月 14 日
編集済み: Roger Stafford 2016 年 6 月 14 日
Your 0.5 is a case where the two nearest integers are equidistant. Mathworks has this to say about the choice they make in such a case. “In the case of a tie, where an element has a fractional part of exactly 0.5, the round function rounds away from zero to the integer with larger magnitude.”
Note that this differs in philosophy from the internal rounding rule used by IEEE ‘double’ or ‘single’ arithmetic operations. In such situations, rounding, where there is a ‘tie’, chooses that result which has a zero in its least significant bit in order to avoid biasing. As you see, Mathworks did not follow that pattern with their ‘round’ function. (I once complained about that many years ago.)
Walter Roberson
Walter Roberson 2016 年 6 月 14 日
IEEE 754 supports a number of rounding modes.
There is the undocumented feature('setround') but it is not documented what the 0.5 setting means

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

回答 (2 件)

Walter Roberson
Walter Roberson 2016 年 6 月 14 日
Are either of dy or d of integer data type? If they are then the calculation would be converted to integer immediately and shan would always be a whole number.
If shan is double, then the exact bit pattern is important in the calculation. You can determine the difference between the value and 1/2 by checking (shan - 0.5) and if the result is negative then shan is slightly less than 0.5 and so would not round up. A value can end up displaying as 0.5 when it is not quite 0.5 but subtracting off 0.5 will quickly tell you whether it reached 0.5 or not.

KSSV
KSSV 2016 年 6 月 14 日
round, rounds the given number to the nearest integer. There are other options in round, you can specify the number of decimal points. Check round(x,N) and use N, accordingly how you expect the result.
  1 件のコメント
Stephen23
Stephen23 2016 年 6 月 14 日
編集済み: Stephen23 2016 年 6 月 14 日
"rounds the given number to the nearest integer" is not a complete answer, because it does not clarify what happens when the input has a fraction of 0.5: which integer is then closest? Different rounding operations resolve this in different ways, and have quite different effects on a set of data as a whole.

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

カテゴリ

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