How to deal with rounding issues when taking log of a sum?

73 Views Asked by At

I am writing some Python3 code, and I need to take the log of the sum of two variables $x_1$ and $x_2$. These variables are given to me in log form as $y_1$ and $y_2$.

In other words...

$y_1 = log(x_1)$

$y_2 = log(x_2)$

And to reiterate, I am only given $y_1$ and $y_2$.

We know the following equality exists...

$log(x_1 + x_2) = log(exp(y_1) + exp(y_2))$

However, $y_1$ and $y_2$ are often very negative values, so $exp(y_1)$ and/or $exp(y_2)$ round to zero. Thus, I cannot accurately calculate $log(x_1 + x_2)$.

How can I circumvent this rounding issue?

1

There are 1 best solutions below

0
On

One simple way is via the mpmath library, which allows for very high precision in calculations. As an example, numpy.exp(-10**5) and math.exp(-10**5) both return 0, while mpmath.exp(-10**5) returns 3.56294956530937e-43430, which Wolfram Alpha agrees with.