Calculating the Log Sum of Exponentials
November 21, 2008
The so-called “log sum of exponentials” is a functional form commonly
encountered in dynamic discrete choice models in economics. It arises
when the choice-specific error terms have a type 1 extreme value
distribution–a very common assumption. In these problems there is
typically a vector
Special care is required to calculate this expression in compiled
languages such as Fortran or C to avoid numerical problems. The
function needs to work for
A simple transformation can avoid both of these problems.
Consider the case where
The following code is a Fortran implementation of a function which
makes the adjustments described above. In order to prevent numerical
overflow, the function shifts the vector v by a constant c,
applies exp and log, and then adjusts the result to account for
the shift.
function log_sum_exp(v) result(e)
real, dimension(:), intent(in) :: v ! Input vector
real :: e ! Result is log(sum(exp(v)))
real :: c ! Shift constant
! Choose c to be the element of v that is largest in absolute value.
if ( maxval(abs(v)) > maxval(v) ) then
c = minval(v)
else
c = maxval(v)
end if
e = log(sum(exp(v-c))) + c
end function log_sum_exp
Note that this function is still not completely robust to very poorly
scaled vectors v and so over- or underflow is still possible (just
much less likely).