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.

4 views (last 30 days)
shan=dy/d;
disy=round(shan);
Even when the value of shan becomes 0.5, the value of disy remains zero
  2 Comments
Roger Stafford
Roger Stafford on 14 Jun 2016
Edited: Roger Stafford on 14 Jun 2016
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.)

Sign in to comment.

Answers (2)

Walter Roberson
Walter Roberson on 14 Jun 2016
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 on 14 Jun 2016
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 Comment
Stephen23
Stephen23 on 14 Jun 2016
Edited: Stephen23 on 14 Jun 2016
"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.

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!