np.arange and np.linspace are both functions in NumPy used to create arrays, but they serve different purposes and have different parameters. Here's a comparison:
np.arange
- Purpose: Generates an array of evenly spaced values within a specified range.
- Parameters:
start: Starting value (default is 0).stop: End value (exclusive).step: Spacing between values (default is 1).
- Example:
import numpy as np arr = np.arange(0, 10, 2) # Output: array([0, 2, 4, 6, 8])
np.linspace
- Purpose: Generates an array of a specified number of evenly spaced values between a start and stop value.
- Parameters:
start: Starting value.stop: End value (inclusive).num: Number of samples to generate (default is 50).endpoint: If True, includes the stop value (default is True).
- Example:
arr = np.linspace(0, 10, num=5) # Output: array([ 0., 2.5, 5., 7.5, 10.])
Key Differences
- Inclusivity:
np.arangeexcludes the stop value, whilenp.linspaceincludes it by default. - Control:
np.arangeis controlled by the step size, whilenp.linspaceis controlled by the number of samples.
When to Use
- Use
np.arangewhen you know the step size you want. - Use
np.linspacewhen you want a specific number of points between two values.
Feel free to try both functions to see how they work in practice!
