I need to write a function that converts a binary fraction number into decimal fraction number in R. e.g. f(0.001) # 0.125
What I did: I searched for the related functions in R packages:
DescTools::BinToDec(0.001) # NA
DescTools::BinToDec("0.001") # NA
base::strtoi(0.001, base=2) # NA
base::strtoi("0.001", base=2) # NA
base::packBits(intToBits(0.001), "integer") # 0
base::packBits(intToBits("0.001"), "integer") # 0
compositions::unbinary(0.001) # 0.001
compositions::unbinary("0.001") # NA
I searched in SOF, found the following:
base2decimal <- function(base_number, base = 2) {
split_base <- strsplit(as.character(base_number), split = "")
return(sapply(split_base, function(x) sum(as.numeric(x) * base^(rev(seq_along(x) - 1)))))}
base2decimal(0.001) # NA
base2decimal("0.001") # NA
0.001 is:
(0 * 2^(-1)) + (0 * 2^(-2)) + (1 * 2^(-3)) # 0.125
(0 * 1/2) + (0 * (1/2)^2) + (1 * (1/2)^3) # 0.125
(0 * 0.5) + (0 * (0.5)^2) + (1 * 0.5^3) # 0.125
So, something like sum of the inner product (0,0,1) * (0.5^1, 0.5^2, 0.5^3)
seems to finish the problem, I could not figure out how to do this in general case.
javascript case:
How to convert a binary fraction number into decimal fraction number?
How to convert binary fraction to decimal
lisp case:
Convert fractions from decimal to binary