Excluding 0.5 from rounding
3 ビュー (過去 30 日間)
古いコメントを表示
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?
0 件のコメント
採用された回答
John D'Errico
2022 年 1 月 13 日
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]
xr = strangeround(x)
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
0 件のコメント
その他の回答 (1 件)
Max Heimann
2022 年 1 月 13 日
編集済み: Max Heimann
2022 年 1 月 13 日
if mod(x,1) ~= 0.5
x = round(x)
end
3 件のコメント
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
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.
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!