bundles / scipy latest / scipy / special / _logsumexp / logsumexp
function
scipy.special._logsumexp:logsumexp
source: build-install/usr/lib/python3.14/site-packages/scipy/special/_logsumexp.py:15
Signature
def logsumexp(a, axis = None, b = None, keepdims = False, return_sign = False)Summary
Compute the log of the sum of exponentials of input elements.
Parameters
a: array_likeInput array.
axis: None or int or tuple of ints, optionalAxis or axes over which the sum is taken. By default
axisis None, and all elements are summed.b: array-like, optionalScaling factor for exp(
a) must be of the same shape asaor broadcastable toa. These values may be negative in order to implement subtraction.keepdims: bool, optionalIf this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original array.
return_sign: bool, optionalIf this is set to True, the result will be a pair containing sign information; if False, results that are negative will be returned as NaN. Default is False (no sign information).
Returns
res: ndarrayThe result,
np.log(np.sum(np.exp(a)))calculated in a numerically more stable way. Ifbis given thennp.log(np.sum(b*np.exp(a)))is returned. Ifreturn_signis True,rescontains the log of the absolute value of the argument.sgn: ndarrayIf
return_signis True, this will be an array of floating-point numbers matching res containing +1, 0, -1 (for real-valued inputs) or a complex phase (for complex inputs). This gives the sign of the argument of the logarithm inres. Ifreturn_signis False, only one result is returned.
Notes
NumPy has a logaddexp function which is very similar to logsumexp, but only handles two arguments. logaddexp.reduce is similar to this function, but may be less stable.
The logarithm is a multivalued function: for each there is an infinite number of such that . The convention is to return the whose imaginary part lies in .
Examples
import numpy as np from scipy.special import logsumexp a = np.arange(10)✓
logsumexp(a) np.log(np.sum(np.exp(a)))✗
np.float64(9.45862974442671)With weights
a = np.arange(10) b = np.arange(10, 0, -1)✓
logsumexp(a, b=b) np.log(np.sum(b*np.exp(a)))✗
np.float64(9.917017853303465)Returning a sign flag
logsumexp([1,2],b=[1,-1],return_sign=True)
✗(np.float64(1.5413248546129181), np.float64(-1.0))Notice that `logsumexp` does not directly support masked arrays. To use it on a masked array, convert the mask into zero weights:
a = np.ma.array([np.log(2), 2, np.log(3)], mask=[False, True, False]) b = (~a.mask).astype(int)✓
logsumexp(a.data, b=b), np.log(5)
✗(np.float64(1.6094379124341005), np.float64(1.6094379124341003))
See also
- numpy.logaddexp
- numpy.logaddexp2
Aliases
scipy.special.logsumexp