Decimal to Binary Representation
Purpose
How to represent a fraction in binary format
> GetBinaryRep <- function(x, n = 52) { + result <- vector() + for (i in 1:n) { + x <- 2 * x + result <- c(result, x) + if (x > 1) + x <- x - 1 + } + return(ifelse(result > 1, 1, 0)) + } > x <- 0.274 > print(GetBinaryRep(x, 100)) [1] 0 1 0 0 0 1 1 0 0 0 1 0 0 1 0 0 1 1 0 1 1 1 0 1 0 0 1 0 1 1 1 1 0 0 0 1 1 [38] 0 1 0 1 0 0 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 [75] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 |
> plot(GetBinaryRep(x, 100), pch = 19) |
As you can any decimal ends up with a recurring pattern OR
gets rounded off based on the mantissa allowed in the floating point arithmetic