Range and Linspace Arrays
Generate numerical sequences with controlled increments, create evenly spaced values, understand endpoint behavior, and select the right function for your numerical tasks.
1. Learning Objectives
By the end of this lesson, you will be able to:
- Explain the purpose of
np.arange(). - Generate sequences using start, stop, and step values.
- Create evenly spaced values using
np.linspace(). - Control the number of generated values and endpoint inclusion.
- Generate descending sequences.
- Understand important differences between the two functions.
- Apply these functions to practical numerical problems.
2. Introduction to Numerical Sequences
A numerical sequence is an ordered collection of values. In programming, sequences are useful for generating indexes, measurements, time intervals, mathematical inputs, and test data.
NumPy provides two useful functions for generating sequences:
np.arange() and np.linspace().
Both create arrays, but they let you control the generated
values in different ways.
Example: Generate a Simple Sequence
import numpy as np numbers = np.arange(1, 6) print(numbers)
Output:
[1 2 3 4 5]
The generated array contains integers starting at 1 and stopping before 6.
3. Understanding np.arange()
The np.arange() function generates values
separated by a specified step size.
General syntax:
np.arange(start, stop, step)
| Parameter | Description | Default Behavior |
|---|---|---|
start |
The beginning of the sequence. | Defaults to 0 if omitted. |
stop |
The boundary where generation stops. | Required. |
step |
The increment between values. | Defaults to 1. |
Example 1: Start and Stop
values = np.arange(2, 8) print(values)
Output:
[2 3 4 5 6 7]
Example 2: Custom Step Size
values = np.arange(0, 15, 3) print(values)
Output:
[ 0 3 6 9 12]
Example 3: Odd Numbers
odd_numbers = np.arange(1, 12, 2) print(odd_numbers)
Output:
[ 1 3 5 7 9 11]
np.arange(2, 8), the last value is 7,
not 8.
4. Generating Descending Sequences
A negative step allows np.arange() to generate
values in descending order. The starting value must be
greater than the stop boundary for a typical descending sequence.
Example: Count Backwards
countdown = np.arange(10, 0, -2) print(countdown)
Output:
[10 8 6 4 2]
Example: Descending Integers
numbers = np.arange(5, -1, -1) print(numbers)
Output:
[5 4 3 2 1 0]
5. Understanding np.linspace()
The np.linspace() function creates a specified
number of evenly spaced values between a starting value
and an ending value.
General syntax:
np.linspace(start, stop, num=50, endpoint=True)
| Parameter | Description |
|---|---|
start |
The first value in the interval. |
stop |
The ending boundary. |
num |
The number of values to generate. Defaults to 50. |
endpoint |
Controls whether the stop value is included. Defaults to true. |
Example 1: Five Evenly Spaced Values
values = np.linspace(0, 20, num=5) print(values)
Output:
[ 0. 5. 10. 15. 20.]
Example 2: Four Values Between 2 and 8
values = np.linspace(2, 8, num=4) print(values)
Output:
[2. 4. 6. 8.]
Example 3: Exclude the Endpoint
values = np.linspace(
0,
10,
num=5,
endpoint=False
)
print(values)
Output:
[0. 2. 4. 6. 8.]
np.linspace() when
you know how many evenly spaced points you need.
6. Visualizing the Difference
In the examples above, the numerical results are similar.
However, np.arange() calculates values from
a step size, while np.linspace() calculates
values based on the requested number of points.
7. Understanding Step Size in np.linspace()
When the endpoint is included and more than one point is requested, the spacing between adjacent values is:
Spacing formula:
\[ \text{Spacing} = \frac{\text{stop} - \text{start}}{\text{num} - 1} \]
For example, if the start is 0, the stop is 12, and the number of points is 4, the spacing is:
\[ \frac{12 - 0}{4 - 1} = 4 \]
values = np.linspace(0, 12, num=4) print(values)
Output:
[ 0. 4. 8. 12.]
np.linspace() returns that single
point at the start value. Do not use the spacing formula
with num=1, because it would divide by zero.
8. Comparing np.arange() and np.linspace()
| Feature | np.arange() |
np.linspace() |
|---|---|---|
| Main parameters | Start, stop, step. | Start, stop, number of points. |
| Stop value | Excluded. | Included by default. |
| Control over count | Indirect, based on range and step. | Directly controlled by num. |
| Best suited for | Integer sequences and regular increments. | A fixed number of evenly spaced values. |
| Floating-point step behavior | Floating-point precision can affect generated values. | Useful when the number of points is more important than the step. |
Example: Compare Different Requirements
import numpy as np
# Generate values at intervals of 5.
step_values = np.arange(0, 21, 5)
# Generate exactly five points between 0 and 20.
point_values = np.linspace(0, 20, num=5)
print("Step-Based:", step_values)
print("Point-Based:", point_values)
Output:
Step-Based: [ 0 5 10 15 20] Point-Based: [ 0. 5. 10. 15. 20.]
9. Practical Program: Generate Measurement Values
At CIIT TRANING INSTITUTE, Samiksha is preparing a set of measurement points for a numerical exercise. She needs a regular integer sequence and a fixed number of evenly spaced decimal values.
Complete Program
import numpy as np
measurement_steps = np.arange(0, 51, 10)
measurement_points = np.linspace(0, 1, num=6)
print("Measurement Steps:")
print(measurement_steps)
print("Measurement Points:")
print(measurement_points)
print("Number of Steps:", measurement_steps.size)
print("Number of Points:", measurement_points.size)
Output:
Measurement Steps: [ 0 10 20 30 40 50] Measurement Points: [0. 0.2 0.4 0.6 0.8 1. ] Number of Steps: 6 Number of Points: 6
The first array increases in increments of 10. The second array contains six evenly spaced values from 0 through 1.
10. Common Mistakes and Best Practices
1. Expecting np.arange() to Include Stop
The stop boundary is excluded. Check whether the last value you need is included in the generated sequence.
2. Confusing Step and Number of Points
Use step with np.arange()
and num with np.linspace().
3. Using the Wrong Step Direction
A descending sequence usually requires a negative step. An ascending sequence usually requires a positive step.
4. Assuming Floating-Point Values Are Exact
Decimal values may be represented approximately in binary floating-point. Avoid relying on exact equality when comparing computed decimal values.
5. Forgetting Endpoint Settings
The endpoint parameter in
np.linspace() defaults to true. Set it
to false when the final boundary should be excluded.
11. Classroom Practice Activity
Activity: Generate and Compare Sequences
Samadhan, Pradnya, and Samiksha can complete this activity to practice sequence generation.
- Generate integers from 1 through 15 using
np.arange(). - Generate even numbers from 2 through 30.
- Create a descending sequence from 20 to 0 in steps of -5.
- Generate exactly five evenly spaced values between 0 and 100.
- Generate eight evenly spaced values between -1 and 1.
- Generate five values between 0 and 10 with the endpoint excluded.
- Display the shape and size of each generated array.
Starter Code
import numpy as np
sequence = np.arange(1, 16)
even_numbers = np.arange(2, 31, 2)
descending = np.arange(20, -1, -5)
five_points = np.linspace(0, 100, num=5)
decimal_points = np.linspace(-1, 1, num=8)
excluded_endpoint = np.linspace(
0,
10,
num=5,
endpoint=False
)
print("Sequence:", sequence)
print("Even Numbers:", even_numbers)
print("Descending:", descending)
print("Five Points:", five_points)
print("Decimal Points:", decimal_points)
print("Endpoint Excluded:", excluded_endpoint)
print("Sequence Shape:", sequence.shape)
print("Decimal Points Size:", decimal_points.size)
Review Questions
- What is the main purpose of
np.arange()? - Why is the stop value excluded from an
np.arange()result? - What does the
stepparameter control? - What is the role of
numinnp.linspace()? - How can you exclude the endpoint in
np.linspace()? - How do you create a descending sequence?
- When should you prefer
np.linspace()overnp.arange()? - What spacing is produced by
np.linspace(0, 12, num=4)?
Summary
In this lesson, you learned to generate numerical sequences
using np.arange() and evenly spaced values
using np.linspace().
You explored start, stop, and step parameters, descending sequences, endpoint control, and the difference between controlling a step size and controlling the number of points.