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.


 

  • np.e ≈ 2.71828


 2. Base-2 Logarithm (np.log2)

  • Computes the logarithm base 2 of each element.


 

  • Useful in binary computations


 3. Base-10 Logarithm (np.log10)

  • Computes the logarithm base 10 of each element.


 

  • 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


 

  • Useful in data normalization and machine learning


 5. Applying Logs to 2D Arrays


 

  • 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.

You may also like...