Skip to content

Routine for linear interpolation on a grid

Question

Write a function that, given increasing nodes x1<⋯<xnx_1<\dots<x_n with values yiy_i, returns a linearly interpolated value at a query point xx.

Short answer

Find the bracketing interval, then blend linearly. Binary-search for xi≤x≤xi+1x_i\le x\le x_{i+1} in O(log⁡n)O(\log n) and return yi+(yi+1−yi)x−xixi+1−xiy_i+(y_{i+1}-y_i)\tfrac{x-x_i}{x_{i+1}-x_i}. Validate sorted, distinct nodes and decide a policy outside the grid (flat extrapolation, linear extrapolation or an error).

Adapted from Joshi, Denson & Downes, Quant Job Interview Questions and Answers, Q5.16, p.158; question and answer rewritten by SelfMadeQuant.com.

See the hint and the full worked solution in the question bank (free account).

Open the worked solution

Lessons behind this question