How can I do mathematical operations in the base number system n in R

I want to perform some calculations in base 3 and must have addition addition in this base. eg. 2 + 2 should be 11 in base 3

+4
source share
3 answers

The package sfcmischas a function with a name digitsBasethat performs this conversion.

library(sfcmisc)
digitsBase(2+2,base = 3)

# Class 'basedInt'(base = 3) [1:1]
#      [,1]
# [1,]    1
# [2,]    1
+3
source

You can use gmppackage

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

Or write your own function. I changed one of 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)
}

USE

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

, . 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)

hope this helps.

0
source

Source: https://habr.com/ru/post/1687043/


All Articles