如何在R中的基数n系统上执行数学运算

时间:2017-10-06 17:43:28

标签: r binary

我想在base 3中执行一些计算,并且需要在该base中进行加法减法。 例如。 2 + 2应该在基数3中变为11

3 个答案:

答案 0 :(得分:4)

在包let num = "1" if let intNum = Int(num) { // There you have your Integer. } 中,有一个名为sfcmisc的函数可以执行此类转换。

digitsBase

答案 1 :(得分:3)

您可以使用gmp

library(gmp)
as.character(x = as.bigz(2 + 2), b = 3)
#[1] "11"

或编写自己的功能。我修改了here

中的那个
foo = function(dec_n, base){
    BitsInLong = 64
    Digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    if (base < 2 | base > nchar(Digits)){
        stop(paste("The base must be >= 2 and <= ", nchar(Digits)))
    }

    if (dec_n == 0){
        return(0)
    }

    index = BitsInLong
    currentNumber = abs(dec_n)
    charArray = character(0)

    while (currentNumber != 0){
        remainder = as.integer(currentNumber %% base)
        charArray = c(charArray, substr(Digits, remainder + 1, remainder + 1))      
        currentNumber = currentNumber/base
    }

    charArray = inverse.rle(with(rle(rev(charArray)), list(values = if(values[1] == "0"){values[-1]}else{values},
                                                           lengths = if(values[1] == "0"){lengths[-1]}else{lenghts})))

    result = paste(charArray, collapse = "")
    if (dec_n < 0){
        result = paste("-", result)
    }
    return(result)
}

使用

foo(dec_n = 2+2, base = 3)
#[1] "11"

答案 2 :(得分:0)

如果您想将一个数字从一个基数转换为另一个基数,您可以创建以下函数。在这里您可以将数字从基数2转换为36到基数2到36:

baseconverter <- function(number,baseGiven,baseRequire){
  result = c()
  if(baseRequire >36 || baseRequire<2 || baseGiven>36 || baseGiven<2){
    return ("CustomError:Base is not proper")
  }

  Letters = LETTERS[seq( from = 1, to = 26 )]
  numbers = 0:9
  L = c(numbers,Letters)
  rm(numbers)
  rm(Letters)
  number = substring(number,1:nchar(number),1:nchar(number))


  convertToAlpha <- function(a) {
    return(L[a+1])
  }
  alphaToDecimal <- function(a){
    k = match(x = a , table = L )
    return(k-1)
  }

  tempNum = 0
  for (i in rev(number)){
    digit = alphaToDecimal(i)
    if(digit >= baseGiven || digit < 0){
      return ("CustomError:Number is not proper")
    }
    tempNum = (tempNum*baseGiven) + digit
  }

  while(tempNum > baseRequire - 1){
    result = c(convertToAlpha(tempNum - (baseRequire * floor(tempNum/baseRequire))),result)
    tempNum = floor(tempNum/baseRequire)
  }
  result=c(tempNum,result)
  return(paste(result,collapse = ""))
}

您可以使用以下函数将基数m中的数字转换为基数n:

baseconverter(number = 2+2 , baseGiven = 10 , baseRequire = 3)
希望它有所帮助。