w3resource

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


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).

Python-Numpy Code Editor: