How to Use np.logspace in NumPy for Logarithmic Spaced Arrays
Use
np.logspace(start, stop, num) to create an array of num values spaced evenly on a log scale between base**start and base**stop. You can change the base with the base parameter. This is useful for generating values that grow exponentially.Syntax
The basic syntax of np.logspace is:
start: The starting exponent (base raised to this power).stop: The ending exponent.num: Number of samples to generate (default is 50).endpoint: If True, include the stop value (default is True).base: The base of the logarithm (default is 10).dtype: Data type of output array (optional).
python
np.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)
Example
This example creates 5 values spaced evenly on a log scale from 101 (10) to 103 (1000).
python
import numpy as np values = np.logspace(1, 3, num=5) print(values)
Output
[ 10. 31.6227766 100. 316.22776602 1000. ]
Common Pitfalls
One common mistake is confusing start and stop as the actual values instead of their exponents. Remember, np.logspace uses powers of the base, not linear values.
Another pitfall is forgetting that the default base is 10. If you want logarithmic spacing with a different base, you must specify it explicitly.
python
import numpy as np # Wrong: expecting linear spacing between 1 and 1000 wrong = np.logspace(1, 1000, num=5) # This creates huge numbers # Right: use exponents for start and stop right = np.logspace(1, 3, num=5) print('Wrong:', wrong) print('Right:', right)
Output
Wrong: [1.00000000e+01 1.00000000e+250 1.00000000e+499 1.00000000e+749
1.00000000e+999]
Right: [ 10. 31.6227766 100. 316.22776602 1000. ]
Quick Reference
| Parameter | Description | Default |
|---|---|---|
| start | Starting exponent (base^start) | Required |
| stop | Ending exponent (base^stop) | Required |
| num | Number of samples | 50 |
| endpoint | Include stop value | True |
| base | Base of logarithm | 10.0 |
| dtype | Output data type | None |
Key Takeaways
np.logspace creates numbers spaced evenly on a logarithmic scale between powers of a base.
The start and stop parameters are exponents, not the actual values.
Default base is 10, but you can change it with the base parameter.
Use np.logspace to generate exponentially growing sequences easily.
Always check if you want to include the endpoint with the endpoint parameter.