Learn R Programming

VGAM (version 1.1-12)

round2: Rounding of Numbers to Base 2

Description

'round2' works like 'round' but the rounding has base 2 under consideration so that bits (binary digits) beyond a certain theshold are zeroed.

Usage

round2(x, digits10 = 0)

Value

Something similar to round.

Arguments

x

Same as round.

digits10

Same as digits in round. The "10" is to emphasize the usual base 10 used by humans.

Author

T. W. Yee.

Details

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).

See Also

round, tobit.

Examples

Run this code
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

Run the code above in your browser using DataLab