w3resource

NumPy: Compute logarithm of the sum of exponentiations of the inputs


2. Log-Sum-Exp Computation

Write a NumPy program to compute logarithm of the sum of exponentiations of the inputs, sum of exponentiations of the inputs in base-2.

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Calculating the natural logarithm of 1e-50 and 2.5e-50
l1 = np.log(1e-50)
l2 = np.log(2.5e-50)

# Displaying the logarithm of the sum of exponentiations
print("Logarithm of the sum of exponentiations:")
print(np.logaddexp(l1, l2))

# Displaying the logarithm of the sum of exponentiations of the inputs in base-2
print("Logarithm of the sum of exponentiations of the inputs in base-2:")
print(np.logaddexp2(l1, l2)) 

Sample Output:

Logarithm of the sum of exponentiations:                               
-113.876491681                                                         
Logarithm of the sum of exponentiations of the inputs in base-2:       
-113.599555228 

Explanation:

In the above exercise –

l1 and l2 are two small numbers in logarithmic form (logarithms of 1e-50 and 2.5e-50, respectively).

np.logaddexp(l1, l2): This function calculates the natural logarithm of the sum of the exponentials of l1 and l2, i.e., log(exp(l1) + exp(l2)).

np.logaddexp2(l1, l2): Similar to logaddexp() function, this function calculates the base-2 logarithm of the sum of the exponentiations (in base 2) of l1 and l2, i.e., log2(2**l1 + 2**l2).


For more Practice: Solve these Related Problems:

  • Implement a function that calculates the log-sum-exp of an array for numerical stability.
  • Compute the log-sum-exp in base-2 and compare the result with the natural logarithm version.
  • Apply vectorized operations to compute the log of the sum of exponentials for multi-dimensional arrays.
  • Test the function on arrays with large positive and negative values to avoid overflow issues.

Go to:


PREV : Element-wise Arithmetic Operations
NEXT : True Division of Array Inputs

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.