w3resource

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

NumPy Mathematics: Exercise-35 with Solution

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:

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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://198.211.115.131/python-exercises/numpy/python-numpy-math-exercise-35.php