Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i perform mathematical operations on a base n number system in R

Tags:

r

binary

I want to perform some calculations in base 3 and need to have addition subtraction in that base. eg. 2+2 should become 11 in base 3

like image 770
whisperer Avatar asked Mar 07 '23 21:03

whisperer


2 Answers

In the package sfcmisc there is a function called digitsBase that does such conversion.

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

# Class 'basedInt'(base = 3) [1:1]
#      [,1]
# [1,]    1
# [2,]    1
like image 139
Therkel Avatar answered Mar 10 '23 13:03

Therkel


You may be able to use gmp package

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

Or write your own function. I modified the one from 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"
like image 40
d.b Avatar answered Mar 10 '23 14:03

d.b