torch.linspace
function linspace(start: number, end: number, steps: number, options: TensorOptions = {}): TensorCreate a tensor with linearly spaced values.
Returns a 1-D tensor with a fixed number of evenly spaced values between start and end (both inclusive). Unlike arange which uses step size, linspace specifies the total number of points. Useful for creating ranges where the number of points matters more than the step size.
- Inclusive endpoints: Both start and end are included in output
- Fixed points: Number of output elements is always steps (no rounding issues)
- Numeral stability: Computed to minimize floating-point errors
- Edge case: steps=1 returns tensor with just the start value
- Common in ML: Used for creating evaluation grids, sampling ranges, time axes
Parameters
startnumber- Start value (inclusive)
endnumber- End value (inclusive) - always included unlike arange
stepsnumber- Number of values to generate (must be ≥ 1)
optionsTensorOptionsoptional- Optional settings: -
dtype: Data type (default: 'float32') -requires_grad: Enable gradient tracking (default: false) -device: Compute device (default: global device)
Returns
Tensor– A 1-D tensor of shape [steps] with linearly spaced values from start to endExamples
// Fixed number of points regardless of range
const a = torch.linspace(0, 1, 5); // [0, 0.25, 0.5, 0.75, 1]
const b = torch.linspace(-1, 1, 3); // [-1, 0, 1]
const c = torch.linspace(0, 10, 11); // [0, 1, 2, ..., 10] (11 points)
// Single point (edge case)
const single = torch.linspace(5, 10, 1); // [5] (start value only)
// Creating sample points for function evaluation
const x = torch.linspace(-Math.PI, Math.PI, 1000); // 1000 points for plotting
const y = torch.sin(x); // Evaluate sine at sampled points
// Time grid for time-series data
const duration_seconds = 10;
const sampling_rate = 44100; // 44.1 kHz audio
const num_samples = duration_seconds * sampling_rate;
const time_grid = torch.linspace(0, duration_seconds, num_samples);
// Creating evenly-weighted distribution
const num_bins = 100;
const bin_centers = torch.linspace(0, 1, num_bins); // Centers of histogram bins
// Contrast with arange
// arange: specify step size, get variable number of points
const by_step = torch.arange(0, 1, 0.1); // [0, 0.1, 0.2, ..., 0.9]
// linspace: specify number of points, get automatic step size
const by_count = torch.linspace(0, 1, 11); // Always 11 points, spacing determinedSee Also
- PyTorch torch.linspace()
- arange - Create range by step size instead of point count
- logspace - Create exponentially spaced values with fixed points
- meshgrid - Create 2D/3D grids from 1D linspace tensors