w3resource

NumPy: Compute the natural logarithm of one plus each element of a given array in floating-point accuracy


35. Compute log1p (Natural Logarithm of 1 + x)

Write a NumPy program to compute the natural logarithm of one plus each element of a given array in floating-point accuracy.

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Creating an array with two very small numbers
x = np.array([1e-99, 1e-100])

# Displaying the original array
print("Original array: ")
print(x)

# Calculating natural logarithm of one plus each element in the array
print("\nNatural logarithm of one plus each element:")
print(np.log1p(x)) 

Sample Output:

Original array: 
[1.e-099 1.e-100]

Natural logarithm of one plus each element:
[1.e-099 1.e-100]

Explanation:

In the above exercise –

x = np.array([1e-99, 1e-100]): This line creates a NumPy array x with two very small values - 1e-99 and 1e-100.

np.log1p(x): This line calculates the natural logarithm of 1 + x for each element of the x array. Since the values in the x array are very small, the values of 1 + x will be very close to 1, and the natural logarithm of 1 + x will be very close to x. Therefore, the output of np.log1p(x) will be very close to the values of x itself.


For more Practice: Solve these Related Problems:

  • Implement a function that uses np.log1p to compute the natural logarithm of one plus each element of an array.
  • Test the function on an array with very small values to ensure numerical stability.
  • Create a solution that compares np.log1p(x) with np.log(1 + x) for a range of test inputs.
  • Apply the function on a multi-dimensional array and verify that the output shape is preserved.

Python-Numpy Code Editor:

Previous: Write a NumPy program to compute natural, base 10, and base 2 logarithms for all elements in a given array.

Next: Write a NumPy program to check element-wise True/False of a given array where signbit is set.

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.