Resize, rotate or warp an image and you end up needing the pixel at position (1.7, 2.3) — a place where no pixel exists. Bilinear interpolation invents it, by blending the four pixels surrounding that spot in proportion to how close each one is.
Task: write bilinear(grid, x, y) returning the interpolated value, rounded to 4 decimal places.
The coordinate convention, since this is where everyone gets confused: x is the column, y is the row. So the value at whole coordinates (x, y) is grid[y][x].
The method:
x0 = floor(x), y0 = floor(y) — the top-left of the four surrounding pixels. x1 = x0 + 1, y1 = y0 + 1.dx = x - x0, dy = y - y0 — how far along you are between them, each between 0 and 1.x twice, once on the top row and once on the bottom:
top = (1 - dx) * grid[y0][x0] + dx * grid[y0][x1]bottom = (1 - dx) * grid[y1][x0] + dx * grid[y1][x1]y: (1 - dy) * top + dy * bottom.x can be exactly the last column — where x0 + 1 runs off the edge — so clamp x1 to width - 1 and y1 to height - 1. With dx = 0 there the out-of-range neighbour carries no weight anyway.y first and you get the identical number.At the exact centre of four pixels, all four weights are 0.25 and you get their plain average — a good first check.