[R] Exponentiate very large numbers
William Dunlap
wdunlap at tibco.com
Tue Feb 5 19:01:55 CET 2013
> Are there any tricks I can use to get a real result
> for exp( ln(a) ) - exp( ln(0.1) + ln(b) ), either in logarithm or
> exponential form?
log.a <- 1347
log.b <- 1351
f0 <- function(log.a, log.b) exp(log.a) - exp(log(0.1) + log.b)
will not work because f0(1347,1351) is too big to represent as
a double precision number (abs(result)>10^308)).
If you are satisfied with computing log(result) you can do it
with some helper function:
addOnLogScale <- function (e1, e2)
{
# log(exp(e1) + exp(e2))
small <- pmin(e1, e2)
big <- pmax(e1, e2)
log1p(exp(small - big)) + big
}
subtractOnLogScale <- function (e1, e2)
{
# log(abs(exp(e1) - exp(e2)))
small <- pmin(e1, e2)
big <- pmax(e1, e2)
structure(log1p(-exp(small - big)) + big, isPositive = e1 > e2)
}
as
f1 <- function(log.a, log.b) {
# log(abs(exp(log.a) - exp( log(0.1) + log.b))), avoiding overflow
subtractOnLogScale( log.a, log(0.1) + log.b )
}
E.g.,
> f0(7,3)
[1] 1094.625
> exp(f1(7,3))
[1] 1094.625
attr(,"isPositive")
[1] TRUE
With your log.a and log.b we get
> f1(1347, 1351)
[1] 1348.495
attr(,"isPositive")
[1] FALSE
You can use the Rmpfr package to compute the results to any desired precision.
Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf
> Of francesca casalino
> Sent: Monday, February 04, 2013 8:00 AM
> To: r-help at r-project.org
> Subject: Re: [R] Exponentiate very large numbers
>
> I am sorry I have confused you, the logs are all base e:
>
> ln(a) = 1347
> ln(b) = 1351
>
> And I am trying to solve this expression:
>
> exp( ln(a) ) - exp( ln(0.1) + ln(b) )
>
>
> Thank you.
>
> 2013/2/4 francesca casalino <francy.casalino at gmail.com>:
> > Dear R experts,
> >
> > I have the logarithms of 2 values:
> >
> > log(a) = 1347
> > log(b) = 1351
> >
> > And I am trying to solve this expression:
> >
> > exp( ln(a) ) - exp( ln(0.1) + ln(b) )
> >
> > But of course every time I try to exponentiate the log(a) or log(b)
> > values I get Inf. Are there any tricks I can use to get a real result
> > for exp( ln(a) ) - exp( ln(0.1) + ln(b) ), either in logarithm or
> > exponential form?
> >
> >
> > Thank you very much for the help
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list