.log10()

MamtaWardhani's avatar
Published Jun 24, 2024Updated May 22, 2025
Contribute to Docs

NumPy’s .log10() function calculates the base-10 logarithm of input values element-wise. It computes the power to which 10 must be raised to obtain a given number. It’s a key tool for applying logarithmic transformations in numerical computing.

The .log10() function is widely used in various fields such as data science, signal processing, and scientific computing. It helps visualize data spanning multiple orders of magnitude, simplifies multiplicative relationships into additive ones, and is crucial for applications like sound analysis (decibel calculations), pH measurements in chemistry, earthquake magnitude (Richter scale), and creating log-scale visualizations.

Syntax

numpy.log10(x, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True)

Parameters:

  • x: Input array or scalar value for which to calculate the base-10 logarithm.
  • out(Optional): Output array to store results. Must have the same shape as the expected output.
  • where(Optional): Boolean array or condition specifying where to calculate the logarithm.
  • casting(Optional): Controls what kind of data casting may occur during the operation.
  • order(Optional): Memory layout for the output array.
  • dtype(Optional): Data type for the output. If not specified, the data type of the input is used.
  • subok(Optional): If True, allow subclasses of ndarray.

Return value:

The function returns an ndarray containing the base-10 logarithm of each element in x. For negative input values, it returns NaN (Not a Number).

Example 1: Basic Usage of the .log10() method in NumPy

This example demonstrates how to calculate the base-10 logarithm of various numbers using NumPy’s .log10() function:

import numpy as np
# Create an array of values
values = np.array([1, 10, 100, 1000])
# Calculate the base-10 logarithm
result = np.log10(values)
# Display the result
print("Original values:", values)
print("Base-10 logarithms:", result)
# Base-10 logarithm of a single value
single_value = 10000
print(f"log10({single_value}) =", np.log10(single_value))
# Working with negative or zero values
mixed_values = np.array([100, 10, 1, 0, -10])
print("Mixed values:", mixed_values)
print("Base-10 logarithms (with warnings):", np.log10(mixed_values))

The output generated by this code will be:

Original values: [1 10 100 1000]
Base-10 logarithms: [0. 1. 2. 3.]
log10(10000) = 4.0
Mixed values: [ 100 10 1 0 -10]
Base-10 logarithms (with warnings): [ 2. 1. 0. -inf nan]

This example shows that .log10() returns the expected mathematical results: log10(1)=0, log10(10)=1, log10(100)=2, etc. For zero, it returns negative infinity, and for negative numbers, it returns NaN.

Example 2: Visualizing Logarithmic Data

This example creates a visual comparison between linear and logarithmic scales, which is useful for datasets that span multiple orders of magnitude:

import numpy as np
import matplotlib.pyplot as plt
# Generate data with exponential growth
x = np.linspace(0, 5, 100)
y = np.power(10, x) # Values will range from 1 to 100,000
# Create a figure with two subplots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
# Plot on linear scale
ax1.plot(x, y, 'b-')
ax1.set_title('Linear Scale')
ax1.set_xlabel('x')
ax1.set_ylabel('y = 10^x')
ax1.grid(True)
# Plot on log scale (equivalent to plotting log10(y) on a linear scale)
ax2.plot(x, np.log10(y), 'r-')
ax2.set_title('Logarithmic Scale (base-10)')
ax2.set_xlabel('x')
ax2.set_ylabel('log10(y)')
ax2.grid(True)
plt.tight_layout()
plt.show()
# Print some values to understand the transformation
sample_points = [0, 1, 2, 3, 4, 5]
for point in sample_points:
value = 10**point
log_value = np.log10(value)
print(f"x = {point}, y = {value}, log10(y) = {log_value}")

The output of the above code will be:

x = 0, y = 1.0, log10(y) = 0.0
x = 1, y = 10.0, log10(y) = 1.0
x = 2, y = 100.0, log10(y) = 2.0
x = 3, y = 1000.0, log10(y) = 3.0
x = 4, y = 10000.0, log10(y) = 4.0
x = 5, y = 100000.0, log10(y) = 5.0

Two side-by-side plots showing exponential growth on a linear scale and its transformation to a straight line on a base-10 logarithmic scale

This example demonstrates how .log10() can transform exponentially growing data into a linear relationship, making it easier to visualize and analyze data that spans multiple orders of magnitude.

Codebyte Example: Analyzing Sound Intensity

This example demonstrates how to use .log10() to calculate decibel levels from sound pressure measurements, a common application in audio engineering and acoustics.

Code
Output
Loading...

This example demonstrates how logarithmic scales are essential for representing sound levels in a way that corresponds to human perception, using .log10() to convert between linear pressure measurements and logarithmic decibel values.

Frequently Asked Questions

1. What happens when I use .log10() on zero or negative numbers?

For zero values, .log10() returns negative infinity (-inf). For negative values, it returns NaN (Not a Number) since logarithms of negative numbers are not defined in the real number system.

2. How does NumPy’s .log10() compare to using np.log(x)/np.log(10)?

Both approaches calculate the base-10 logarithm, but .log10() is optimized for this specific calculation and is typically faster and more numerically stable than the division approach.

3. Can I use .log10() on complex numbers?

Yes, NumPy’s .log10() supports complex numbers. For a complex input, it returns the complex base-10 logarithm.

4. How do I handle data that includes zeros or negative values when I need to apply a logarithmic transformation?

Common strategies include:

  • Adding a small constant to all values: np.log10(data + epsilon)
  • Using only positive values: np.log10(data[data > 0])
  • Using a symmetric log transformation like np.sign(data) * np.log10(1 + np.abs(data))

5. Is there a way to specify a different base for logarithms in NumPy?

Yes, you can use the np.log() function with the change of base formula: np.log(x) / np.log(base). NumPy also provides specific functions for common bases: np.log10() for base-10, np.log2() for base-2, and np.log() or np.log1p() for the natural logarithm.

All contributors

Contribute to Docs

Learn Python:NumPy on Codecademy