Search code examples
rloggingrepresentationunderflow

taking number parts in R (rescale small numbers using log function)


I want to represent the following number using the log function:

2.5e-600/1.7e-500

here is what I did on paper, and what I would like to automate on R for any given number:

log(2.5e-600/1.7e-500) = log(2.5e-600)-log(1.7e-500)
                      = log(2.5)-600*log(10) - log(1.7) + 500*log(10)
                      = -229.8728

However, I am thinking that on R it won't be as straight forward to go from log(10^-600) to -600*log(10). Because R evaluates the inside expression first then applies the log function which gives -Inf instead of -1381.511

My question is how can I remedy to that problem? I am thinking that maybe there is a function that would allow me to retrieve the exponent part of a number ? same question for going from log(2.5e-600) to log(2.5)-600*log(10)


Solution

  • For this special case, you can do it fairly straightforwardly without using mpfr:

    x1 <- "2.5e-600"
    x2 <- "1.7e-500"
    

    Split value into mantissa and exponent (log10):

    get_num <- function(x) {
        as.numeric(strsplit(x,"e")[[1]])
    }
    val1 <- get_num(x1)
    val2 <- get_num(x2)
    

    Now take the ratio of the mantissas (log(v1)-log(v2)), but subtract the exponents:

    log(val1[1])-log(val2[1])+log(10^(val1[2]-val2[2]))
    ## [1] -229.8728