如何在R中将二进制分数转换为十进制分数?

时间:2019-06-01 22:58:08

标签: r decimal base fractions

我需要编写一个将R中的二进制分数转换为十进制分数的函数。 template <class Type> class unorderedLinkedList : public linkedListType<Type> { public: bool search(const Type& searchItem) const { nodeType<Type>* first; nodeType<Type>* last; nodeType<Type>* current; bool found = false; current = first; while (current != nullptr && !found) if (current->info == searchItem) found = true; else current = current->link; return found; } void insertFirst(const Type& newItem) { nodeType<Type>* first; nodeType<Type>* last; nodeType<Type>* newNode; newNode = new nodeType<Type>; newNode->info = newItem; newNode->link = first; first = newNode; count++; if (last == nullptr) last = newNode; } void insertLast(const Type& newItem) { nodeType<Type>* first; nodeType<Type>* last; nodeType<Type>* newNode; newNode = new nodeType<Type>; newNode->info = newItem; newNode->link = nullptr; if (first == nullptr) { first = newNode; last = newNode; count++; } else { last->link = newNode; last = newNode; count++; } } void deleteNode(const Type& deleteItem) { nodeType<Type>* first; nodeType<Type>* last; nodeType<Type>* current; nodeType<Type>* trailCurrent; bool found; if (first == nullptr) cout << "Cannot delete from an empty list." << endl; else { if (first->info == deleteItem) { current = first; first = first->link; count--; if (first == nullptr) last = nullptr; delete current; } else { found = false; trailCurrent = first; current = first->link; while (current != nullptr && !found) { if (current->info != deleteItem) { trailCurrent = current; current = current->link; } else found = true; } if (found) { trailCurrent->link = current->link; count--; if (last == current) last = trailCurrent; delete current; } else cout << "The item to be deleted is not in " << "the list." << endl; } } } };

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

f(0.001) # 0.125

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

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

0.001是:

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 * 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 之类的东西似乎可以解决问题,在一般情况下,我不知道该怎么做。

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

2 个答案:

答案 0 :(得分:1)

您可以扩展问题中发布的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

答案 1 :(得分:0)

library(cwhmisc) # int, frac
from2to10 <- function(n) {
SignOfNumber <- ""
if (n < 0) {
n <- abs(n)
SignOfNumber <- "-"}

nWhole <- int(n)
nWhole <- as.character(nWhole)

nFraction <- frac(n)
nFraction <- as.character(nFraction)

DecimalWhole   <- sapply(strsplit(nWhole, split=""), function(x) sum(as.numeric(x) * 2^(rev(seq_along(x) - 1))))

if (nFraction == 0) {
DecimalFraction <- ""
paste0(SignOfNumber, DecimalWhole)
} else { # Find decimal fraction part

part3 <- function(x, y, z) { eval(parse(text=(paste(x, y, z,sep="")))) }
y <- as.numeric(strsplit(substr(part3("\"",n,"\""), which(strsplit(part3("\"",n,"\""), "")[[1]]==".") + 1, nchar(part3("\"",n,"\""))),"")[[1]])
DecimalFraction <- sum(y * (0.5^(1:length(y))))
paste0(SignOfNumber, DecimalWhole + DecimalFraction)
}
}

from2to10(0.001) # "0.125"
as.numeric(from2to10(0.001)) # 0.125