I would like to round a matrix M
to arbitrary precision in Rcpp. It is particularly easy to do so in R:
M <- matrix(rnorm(4), 2, 2)
M
[,1] [,2]
[1,] 0.04463484 0.1455878
[2,] 1.77416096 1.0787835
round(M,2)
[,1] [,2]
[1,] 0.04 0.15
[2,] 1.77 1.08
That turns out to be slightly challenging in Rcpp / C++.
There is a round()
function, however, it unfortunately only rounds to the nearest integer. For output purposes, e.g. the "%.2f"
format can be used to round to two decimals. If the rounded numbers are to be used in further computations, it is possible to round a single element to arbitrary precision by playing around with floorf
, roundf
and ceilingf
functions using manually adjusted, different scaling factors, see the discussion and proposed solutions here.
Hence, a possible way forward would be to apply above-mentioned approach to each element (or more efficiently, to each column) of the matrix M
. This seems unnecessarily complicated and I was wondering whether one of you has a more efficient/elegant solution for rounding matrices to arbitrary precision in Rcpp.