Exponentiate very large numbers in R

南楼画角 提交于 2019-12-11 06:33:53

问题


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!


回答1:


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...)



回答2:


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))



回答3:


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



来源:https://stackoverflow.com/questions/14691690/exponentiate-very-large-numbers-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!