Katkat

Evaluate piecewise linear function at x

Two SigmaData Scientist · Online Assessment

Last updated

This question evaluates competency in numerical interpolation and handling of piecewise linear functions, including locating the correct segment in a sorted sequence of points and managing out-of-range inputs.

You are given a polyline defined by n 2D points ((x_i, y_i)). Connecting consecutive points with straight line segments forms a piecewise linear function.

Task

Given a target value x, return the corresponding function value y(x):

  • If x equals some x_i, return y_i.
  • If x lies strictly between x_i and x_{i+1}, linearly interpolate on the segment between ((x_i, y_i)) and ((x_{i+1}, y_{i+1})): [ y(x)=y_i + (y_{i+1}-y_i)\cdot\frac{x-x_i}{x_{i+1}-x_i} ]
  • If x < x_0 or x > x_{n-1}, return null (or a sentinel) because the function is undefined outside the polyline.

Input

  • points: list of n pairs (x, y)
  • x: target x-coordinate

Assumptions / Constraints

  • n >= 2
  • Points are given sorted by strictly increasing x (i.e., x0 < x1 < ... < x(n-1)).

Output

  • A numeric value y(x) (float), or null if out of range.