我需要编写一个将R中的二进制分数转换为十进制分数的函数。 f(0.001) # 0.125

我做了什么:我在R包中搜索了相关功能:

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


我在SOF中搜索,发现以下内容:

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是:

(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


因此,类似内部乘积(0,0,1) * (0.5^1, 0.5^2, 0.5^3)的总和似乎可以解决问题,在一般情况下,我不知道如何执行此操作。

JavaScript案例:
How to convert a binary fraction number into decimal fraction number?
How to convert binary fraction to decimal
Lisp案:
Convert fractions from decimal to binary

最佳答案

您可以扩展问题中发布的solution,使其也包括从小数点分隔符的位置开始的两个负数,如下所示:

base2decimal <- function(base_number, base = 2) {
    base_number = paste(as.character(base_number), ".", sep = "")
    return (mapply(function (val, sep) {
                      val = val[-sep];
                      if (val[[1]] == "-") {
                          sign = -1
                          powmax = sep[[1]] - 3
                          val = val[-1]
                      } else {
                          sign = 1
                          powmax = sep[[1]] - 2
                      };
                      sign * sum(as.numeric(val) * (base ^ seq(powmax, by = -1, length = length(val))))},
        strsplit(base_number, NULL), gregexpr("\\.", base_number)))
}


此代码还适用于小于(或等于)10的其他基数:

base2decimal(c('0.101', '.101', 0.101, 1101.001, 1101, '-0.101', '-.101', -0.101, -1101.001, -1101))
#[1]   0.625   0.625   0.625  13.125  13.000  -0.625  -0.625  -0.625 -13.125
#[10] -13.000
base2decimal(1110.111)
# 14.875
base2decimal(256.3, 8)
# [1] 174.375

关于r - 如何在R中将二进制分数转换为十进制分数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56411025/

10-12 12:43