Rounding of Numbers to Base 2
'round2' works like 'round' but the rounding has base 2 under consideration so that bits beyond a certain theshold are zeroed.
round2(x, digits10 = 0)
round2()
is intended to allow reliable and safe for ==
comparisons provided both sides have the function applied to the same
value of digits10
.
Internally a numeric has its binary representation (bits) past a certain
point set to all 0s, while retaining a certain degree of accuracy.
Algorithmically, x
is multiplied by 2^exponent
and then
rounded, and then divided by 2^exponent
.
The value of exponent
is approximately 3 * digits10
when
digits10
is positive.
If digits10
is negative then what is returned is
round(x, digits10)
.
The value of exponent
guarantees that x
has been rounded
to at least digits10
decimal places (often around
digits10 + 1
for safety).
Something similar to round
.
T. W. Yee.
set.seed(1); x <- sort(rcauchy(10)) x3 <- round2(x, 3) x3 == round2(x, 3) # Supposed to be reliable (all TRUE) rbind(x, x3) # Comparison (x3[1] * 2^(0:9)) / 2^(0:9) print((x3[1] * 2^(0:11)), digits = 14) # Round to approx 1 d.p. x1 <- round2(x, 1) x1 == round2(x, 1) # Supposed to be reliable (all TRUE) rbind(x, x1) x1[8] == 0.75 # 3/4 print((x1[1] * 2^(0:11)), digits = 9) seq(31) / 32
Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.