How can I exclude the 0.5 fraction from rounding such that the fractions less than or greater than 0.5 are only to be rounded?

 채택된 답변

John D'Errico
John D'Errico 2022년 1월 13일

1 개 추천

You cannot do this. That is, there are only a few specific classes of rounds you can do, embodied in round, fix, floor, and ceil. (I think I listed them all.) There are no flags you can set that will control rounding.
You want to round down, for non-integer parts that are strictly less than 1/2, and round up for non-integer parts greater than 1/2, but leave those values that are exactly at 1/2 alone?
I suppose with some code, and some small effort, do what you want.
x = [1.5;rand(8,1)*10 - 5]
x = 9×1
1.5000 -4.6270 0.9246 -4.6491 1.7999 2.9374 -3.1723 -4.4182 3.1633
xr = strangeround(x)
xr = 9×1
1.5000 -5.0000 1.0000 -5.0000 2.0000 3.0000 -3.0000 -4.0000 3.0000
Does that do as required?
function xround = strangeround(x)
xint = floor(x);
xfrac = x - xint;
xfrac(xfrac < 1/2) = 0;
xfrac(xfrac > 1/2) = 1;
xround = xint + xfrac;
end

추가 답변 (1개)

Max Heimann
Max Heimann 2022년 1월 13일
편집: Max Heimann 2022년 1월 13일

1 개 추천

if mod(x,1) ~= 0.5
x = round(x)
end

댓글 수: 3

John D'Errico
John D'Errico 2022년 1월 13일
Good idea. But while that would work for scalar x, it is not vectorized, and it will fail for vectors and arrays.
Max Heimann
Max Heimann 2022년 1월 13일
편집: Max Heimann 2022년 1월 13일
How about this for vectors and matrices:
% Matrix with test values
x = [0 -4.5 -4.4; 3.3 0.5 1];
% Code
indices = mod(x,1) ~= 0.5;
x(indices) = round(x(indices))
John D'Errico
John D'Errico 2022년 1월 13일
Yes. That will work. And since 0.5 is exactly representable in floating point arithmetic as a double, the exact test for equality is sufficient.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품

릴리스

R2021a

태그

질문:

2022년 1월 13일

댓글:

2022년 1월 13일

Community Treasure Hunt

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

Start Hunting!

Translated by