Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numerically Stable Implementation

I need to compute a normalized exponential of a vector in Matlab.

Simply writing

res = exp(V)/sum(exp(V))

overflows in an element of V is greater than log(realmax) = 709.7827. (I am not sure about underflow conditions.)

How should I implement it to avoid numerical instability?

Update: I received excellent responses about how to avoid overflow. However, I am still happy to hear your thoughts about the possibility of underflow in the code.

like image 636
user25004 Avatar asked May 14 '14 21:05

user25004


1 Answers

The following approach avoids the overflow by subtracting the exponents and then taking the exponential, instead of dividing the exponentials:

res = 1./sum(exp(bsxfun(@minus, V(:), V(:).')))

As a general rule, overflow can be avoided by working in the log domain for as long as possible, and taking the exponential only at the end.

like image 156
Luis Mendo Avatar answered Oct 07 '22 12:10

Luis Mendo