NumPy: Compute logarithm of the sum of exponentiations of the inputs
NumPy Mathematics: Exercise-2 with Solution
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:
Previous: Write a NumPy program to add, subtract, multiply, divide arguments element-wise.
Next: Write a NumPy program to get true division of the element-wise array inputs.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/numpy/python-numpy-math-exercise-2.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics