Compute the natural logarithm with scimath in Python

To compute the natural logarithm with scimath, use the np.emath.log() method in Python NumPy. This function handles complex results automatically, making it safer than the standard np.log() for negative values.

Syntax

np.emath.log(x)

Parameters:

  • x ? The value(s) whose natural logarithm is required. Can be scalar or array.

Returns: The natural logarithm of x. For negative values, returns complex numbers with imaginary parts.

Example with Mixed Values

Let's compute the natural logarithm for various types of values including infinity and negative numbers ?

import numpy as np

# Creating a numpy array with different types of values
arr = np.array([np.inf, -np.inf, np.exp(1), -np.exp(1)])

# Display the array
print("Our Array...")
print(arr)

# Check array properties
print("\nDimensions:", arr.ndim)
print("Datatype:", arr.dtype)
print("Shape:", arr.shape)

# Compute natural logarithm using scimath
result = np.emath.log(arr)
print("\nNatural logarithm (scimath):")
print(result)
Our Array...
[ inf -inf  2.71828183 -2.71828183]

Dimensions: 1
Datatype: float64
Shape: (4,)

Natural logarithm (scimath):
[inf+0.j inf+3.14159265j 1.+0.j 1.+3.14159265j]

Comparison with Standard np.log()

The key difference is how negative values are handled ?

import numpy as np

values = np.array([1, -1, 2, -2])

print("Values:", values)
print("np.emath.log():", np.emath.log(values))

# Standard np.log() would give warnings/NaN for negative values
print("np.log() (with warnings):", np.log(values))
Values: [ 1 -1  2 -2]
np.emath.log(): [0.+0.j        0.+3.14159265j 0.69314718+0.j 0.69314718+3.14159265j]
np.log() (with warnings): [ 0.         nan  0.69314718         nan]

Key Points

  • np.emath.log() returns complex numbers for negative inputs
  • For positive values, results are equivalent to np.log()
  • The imaginary part for negative values is ? (pi)
  • No warnings or NaN values are produced

Conclusion

Use np.emath.log() when you need to compute natural logarithms of arrays that may contain negative values. It provides mathematically correct complex results instead of warnings or NaN values.

---
Updated on: 2026-03-26T19:56:22+05:30

196 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements