w3resource

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


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.

Python-Numpy Code Editor: