user971102
user971102

Reputation: 3075

Exponentiate very large numbers in R

I have the logarithms of very large values, for example:

log_a = 1347 
log_b = 1351 

And I am trying to solve this expression:

exp(log_a) - (0.1 * exp(log_b))

Or equivalently this (same expression just in a different form):

exp( log_a ) - exp( log(0.1) + log_b ) 

But of course every time I try to compute exp(log_a) or exp(log_b) values I get Inf. Are there any tricks I can use to get a real result for exp(log_a) - (0.1 * exp(log_b)), either in logarithm or exponential form?

Thank you very much for the help!

Upvotes: 1

Views: 3683

Answers (3)

Roland
Roland

Reputation: 132706

library(Brobdingnag)
a <- as.brob(exp(1))^1347
a*(1-0.1*exp(4))
#[1] -exp(1348.5)

or calculated manually:

-(exp(1347+log(0.1*exp(4)-1))=-exp(1347+1.4951...)=-exp(1348.4951...)

Upvotes: 10

Jeffrey Sax
Jeffrey Sax

Reputation: 10313

X = exp(log_a) - (0.1 * exp(log_b))
  = exp(log_a) * (1 - 0.1 * exp(log_b) / exp(log_b))
  = exp(log_a) * (1 - exp(-log(10) + log_b - log_a))
  = -exp(log_a) * expm1(-log(10) + log_b - log_a)

expm1 is a built-in function that accurately computes exp(x)-1 for x close to zero. You can get the logarithm of this only if the argument to expm1 is negative so that the entire expression is positive. Then you can just take the logarithm of the absolute value.

log X = log_a + log(-expm1(-log(10) + log_b - log_a))

Upvotes: 4

You can use the gmp library for R, which supports large numbers (arbitrarily big, as far as I know)

for example

> bigz('11111111111111111111111111111111111111111111111111111111111111111111111111111')
Big Integer ('bigz') :
[1] 11111111111111111111111111111111111111111111111111111111111111111111111111111

I presume the exponentiation operator is included somewhere in the package. The manual is here: http://cran.r-project.org/web/packages/gmp/gmp.pdf

Upvotes: 1

Related Questions