r - 如何将二进制小数转换为 R 中的十进制小数?

标签 r decimal base fractions

我需要编写一个函数,将二进制小数转换为 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/

相关文章:

c# - 在 .NET 中除两位小数时出现溢出异常

c# - 删除尾随零

windows - Windows 服务的基类

C Base128 函数

r - 如何“徒手”绘制 Shiny 的形状?

r - 对数据框的每一行进行排序

r - 我如何在 R 中合并两个数据帧但保留所有缺失值。

c# - 如何将 0 小数解析为字符串?

r - 如何在 DT::datatable() 中搜索时停止 xaringan 的键盘快捷键?

html - 当基本 href 设置为该子目录时,如何链接到该子目录中的主 URL?