〰️ Dynamic Time Warping
Aligning time series
DTW = —
vs Euclidean:
Preset signals
Settings
Controls
Stats
DTW distance
Euclidean
Path length
Series len
Info & Theory

Dynamic time warping (DTW) measures how similar two time series are even when they run at different speeds or are shifted in time. It stretches and squeezes the time axis to line up matching shapes.

The cost matrix

For series x (length n) and y (length m) define the local cost d(i,j) = (x_i − y_j)². The accumulated cost obeys the dynamic-programming recurrence

D(i,j) = d(i,j) + min( D(i−1,j), D(i,j−1), D(i−1,j−1) )

with D(0,0)=d(0,0). The heatmap on the right shows D; the bright line is the cheapest warping path from corner to corner, recovered by tracing the minimum predecessors backwards.

DTW vs Euclidean

Plain Euclidean distance compares x_i with y_i at the same index, so a small time shift looks like a huge difference. DTW instead lets index i match several indices j, so two copies of the same shape at different speeds score a small distance — exactly what you need for speech, handwriting and gesture matching.

Sakoe–Chiba band

The optional band forces the path to stay within |i − j| ≤ r. This speeds DTW up and prevents pathological warps, at the cost of disallowing very large time shifts.

About Dynamic Time Warping — Aligning Time Series

Dynamic Time Warping (DTW) is an algorithm that measures similarity between two temporal sequences that may differ in speed, length, or phase by elastically warping the time axis. It builds an accumulated cost matrix using dynamic programming, then traces back the optimal warping path — the cheapest sequence of index pairs that aligns the two series from start to finish. This simulation lets you observe the cost matrix as a heatmap, watch the yellow warping path form, and compare DTW distance against naive Euclidean distance.

DTW was first formalized for automatic speech recognition in the 1970s and remains a cornerstone technique in time-series analysis, bioinformatics, finance, and gesture recognition today.

Frequently Asked Questions

What does Dynamic Time Warping actually measure?

DTW measures the minimum total cost of aligning two time series by allowing each point in one series to match one or more consecutive points in the other. Unlike Euclidean distance, which rigidly pairs points at identical time indices, DTW stretches and compresses the time axis so that similar shapes at different speeds or offsets score a low distance. The result is a single scalar distance: smaller means more similar in shape.

How do I use this simulation?

Choose a preset signal pair (Phase shift, Speed warp, or Two bumps) using the mode buttons on the left panel. Adjust the Sakoe-Chiba band slider to constrain the warping path and the Noise slider to add randomness to the signals, then click Recompute to recalculate. The heatmap on the right shows the accumulated cost matrix D, the yellow diagonal line is the optimal warping path, and the alignment links in the upper-right panel show which indices are matched between the two series.

Why is DTW distance smaller than Euclidean distance for time-shifted signals?

When two signals are identical in shape but shifted in time, Euclidean distance measures the point-by-point mismatch at each index, which can be large even for very similar shapes. DTW instead finds the optimal correspondence between points, effectively sliding and stretching the time axis so that peaks align with peaks and troughs align with troughs. For the Phase shift preset in this simulation, you will typically see DTW distance far below Euclidean distance because DTW absorbs the phase offset at minimal cost.

What is the dynamic programming recurrence behind DTW?

Given series X of length n and Y of length m, define the local cost d(i,j) = (X[i] - Y[j])^2. The accumulated cost matrix D obeys D(i,j) = d(i,j) + min(D(i-1,j), D(i,j-1), D(i-1,j-1)), with D(0,0) = d(0,0). This allows each step to come from the left (repeat Y), above (repeat X), or diagonally (advance both). The DTW distance is sqrt(D(n-1, m-1)) and the optimal path is recovered by greedy back-tracking from the bottom-right corner to the top-left.

What is the Sakoe-Chiba band and why does it matter?

The Sakoe-Chiba band is a global constraint introduced by Hiroaki Sakoe and Seibi Chiba in their 1978 paper that limits the warping path to stay within |i - j| <= r steps of the main diagonal. Without a band, DTW has O(nm) time and space complexity and can produce pathological warps where a single point in one series is matched to the entire other series. Adding a band reduces complexity to O(n * r), prevents extreme warps, and often improves classification accuracy in practice. In this simulation you can see band-constrained cells turn dark in the heatmap.

Where is DTW used in the real world?

DTW is used in speech recognition systems (matching spoken words at different speeds), handwriting and gesture recognition on touchscreens and motion sensors, financial time-series clustering (identifying stocks with similar price trajectories), medical signal analysis (comparing ECG or EEG patterns across patients), and bioinformatics (aligning gene expression time courses). Many modern machine learning libraries such as tslearn and stumpy include optimized DTW implementations for large-scale applications.

What is a common misconception about DTW?

A frequent misconception is that DTW is always better than Euclidean distance for time-series tasks. In reality, for very long series or series with no meaningful time-axis variation, DTW can overfit the warping and actually perform worse than Euclidean distance in classification. Research by Ding et al. (2008) showed that for many benchmark datasets, 1-nearest-neighbor with Euclidean distance is competitive with DTW. The right choice depends on whether temporal distortion is a genuine feature or just noise in your data.

Who invented DTW and when?

The formal dynamic programming formulation of DTW for speech recognition was introduced by Hiroaki Sakoe and Seibi Chiba at NTT in Japan, with their landmark paper "Dynamic programming algorithm optimization for spoken word recognition" published in IEEE Transactions on Acoustics, Speech, and Signal Processing in 1978. However, related elastic matching ideas appeared independently in the early 1970s in work by Vintsyuk (1968, USSR) on speech alignment and Needleman-Wunsch sequence alignment in bioinformatics (1970).

What other algorithms are related to DTW?

DTW is closely related to the Needleman-Wunsch and Smith-Waterman algorithms used for biological sequence alignment, which solve essentially the same dynamic programming problem with different gap penalties. Edit distance (Levenshtein distance) on sequences of symbols is a discrete analogue. For probabilistic modeling of temporal sequences, Hidden Markov Models (HMMs) generalize the DTW idea to a stochastic framework. Uniform Time Warping and Derivative DTW (DDTW), which computes DTW on the first derivative of the series, are direct variants designed to be more shape-focused.

How is DTW used in modern machine learning and engineering?

In engineering and machine learning, DTW serves as the distance metric in k-nearest-neighbor classifiers for time series, as a loss function for sequence-to-sequence neural networks (soft-DTW), and as a similarity measure in time-series clustering and anomaly detection. It is used in industrial IoT to compare sensor readings across machines running at different speeds, in sports analytics to compare athlete movement patterns, and in audio processing to align recordings for time-scale modification without pitch distortion.

What are current research frontiers in time-series alignment?

Active research areas include Soft-DTW, a differentiable approximation of DTW that allows gradient-based optimization and is used as a training loss in neural sequence models. FastDTW and PrunedDTW are approximate algorithms that achieve near-linear time complexity. Shapelet-based methods learn discriminative subsequences rather than computing full pairwise distances. There is also growing interest in optimal transport distances such as the Wasserstein distance as a continuous-domain alternative to DTW, and in GPU-accelerated DTW for very long biomedical and climate time series.