NumPy Logs

πŸ“Š NumPy Logarithmic Functions

NumPy provides a set of vectorized logarithmic functions to perform element-wise logarithmic calculations on arrays. These functions are much faster than using Python’s math library with loops.


βœ… 1. Natural Logarithm (np.log)

  • Computes the natural logarithm (base e) of each element.

import numpy as np

arr = np.array([1, np.e, np.e**2, np.e**3])
log_arr = np.log(arr)

print(log_arr) # [0. 1. 2. 3.]

  • np.e β‰ˆ 2.71828


βœ… 2. Base-2 Logarithm (np.log2)

  • Computes the logarithm base 2 of each element.

arr = np.array([1, 2, 4, 8])
log2_arr = np.log2(arr)

print(log2_arr) # [0. 1. 2. 3.]

  • Useful in binary computations


βœ… 3. Base-10 Logarithm (np.log10)

  • Computes the logarithm base 10 of each element.

arr = np.array([1, 10, 100, 1000])
log10_arr = np.log10(arr)

print(log10_arr) # [0. 1. 2. 3.]

  • Commonly used in scientific notation and pH calculations


βœ… 4. Logarithm of 1 Plus (np.log1p)

  • Computes log(1 + x) accurately for small x

  • Avoids loss of precision for tiny numbers

arr = np.array([1e-10, 1e-5, 0.1])
log1p_arr = np.log1p(arr)

print(log1p_arr)
# [1.00000000e-10 9.99995000e-06 9.53102064e-02]

  • Useful in data normalization and machine learning


βœ… 5. Applying Logs to 2D Arrays

arr2d = np.array([[1, 10], [100, 1000]])
log_arr2d = np.log10(arr2d)

print(log_arr2d)
# [[0. 1.]
# [2. 3.]]

  • Operations are element-wise on all dimensions


βœ… 6. Notes & Tips

  • Logarithms cannot be applied to zero or negative numbers β†’ returns -inf or NaN.

  • Always ensure input array has positive values.

  • Use np.log1p for small values near zero to avoid precision errors.


🎯 Practice Exercises

  1. Create an array [1, 2, 4, 8, 16] and compute log, log2, log10.

  2. Generate 1D array of small numbers [1e-10, 1e-5, 0.1] and use np.log1p.

  3. Create a 2Γ—3 array and compute log10 of all elements.

CodeCapsule

Sanjit Sinha β€” Web Developer | PHP β€’ Laravel β€’ CodeIgniter β€’ MySQL β€’ Bootstrap Founder, CodeCapsule β€” Student projects & practical coding guides. Email: info@codecapsule.in β€’ Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *