Imlerith
Imlerith

Reputation: 489

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)

Upvotes: 0

Views: 204

Answers (2)

Ben Bolker
Ben Bolker

Reputation: 226322

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

Upvotes: 2

AlexR
AlexR

Reputation: 2408

Rs usual numeric format (double) will leave you SOL here, because the numbers you write down are already equal to 0 for R. (Type it out in console: ´2.5e-600´ to get [1] 0 as an answer)

You could take a look at arbitrary precision arithmetic packages for R. A quick google search brought up https://cran.r-project.org/web/packages/Rmpfr/vignettes/Rmpfr-pkg.pdf

> log(mpfr("2.5e-300")/mpfr("1.7e-500"))
1 'mpfr' number of precision  20   bits 
[1] 460.90283

Edit: now that the representation is clear, still use mpfr like this:

N <- mpfr(representable_part) * mpfr("1e-308")^reduction_number

For example

> mpfr(2.5) * mpfr("1e-308")^13
1 'mpfr' number of precision  17   bits 
[1] 2.500098e-4004

Upvotes: 2

Related Questions