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
-inforNaN. -
Always ensure input array has positive values.
-
Use
np.log1pfor small values near zero to avoid precision errors.
π― Practice Exercises
-
Create an array
[1, 2, 4, 8, 16]and compute log, log2, log10. -
Generate 1D array of small numbers
[1e-10, 1e-5, 0.1]and usenp.log1p. -
Create a 2Γ3 array and compute log10 of all elements.
