Floating point overflow. Can this power equation be simplified?

189 Views Asked by At

I’m running into trouble with the following formula that we’re using in our software.

$$ \frac{1 - x^{-y}}{1 - x^{-(y+1)}} $$

In certain cases, the value for $y$ is a relatively large number; sometimes positive, sometimes negative. I just had a case where its value was -13729.03476. Since I’m using ‘regular’ double-precision variables, this led to a floating point overflow error.

Looking at it, I get the distinct impression that it should be possible to simplify this formula, but I just can’t figure out how.

Alternatively, is there some other way to prevent (or predict) a floating point overflow in this situation?

Thanks in advance!

3

There are 3 best solutions below

1
On BEST ANSWER

It's usually very simple. If $x > 1$ and $y$ is positive, or if $x < 1$ and $y$ is negative, then $x^y$ can blow up, so you use the original expression

$$\frac{1 - x^{-y}}{1 - x^{-(y+1)}}$$

If $x > 1$ and $y$ is negative, or if $x < 1$ and $y$ is positive, then $x^{-y}$ can blow up, so you use the expression

$$\frac{x(x^y -1)}{x^{y+1} - 1}$$

But if $x = 1$, then the expression is undefined. I don't know if this can happen in your software, but if so, you need to figure out some way of handling it!

1
On

HINT: i would say this is simplified $$\frac{x \left(x^y-1\right)}{x^{y+1}-1}$$

2
On

Here is an alternate form (courtesy of WolframAlpha):

$$\frac{x(x^y -1)}{x^{y+1} - 1}. $$

I'm not sure, however, if that helps your overflow.

What may help your overflow is to look at \begin{align} \left|\frac{x(x^y-1)}{x^{y+1}-1}\right| &= \exp\left( \ln\left(\left|\frac{x(x^y-1)}{x^{y+1}-1}\right|\right)\right) \\ &=\exp\left(\ln|x(x^y-1)|-\ln|x^{y+1}-1|\right)\\ &=\exp\left(\ln|x| + \ln|x^y-1|-\ln|x^{y+1}-1|\right) \end{align} and computing the inside of $\exp$ first. Something like this:

z:= ln(abs(x)) + ln(abs(x^y-1)) - ln(abs(x^(y+1)-1))
exp(z)

Of course, you have to explicitly take care of the sign of the expression then, but I'll leave that to you.