interpolation polynomial in javascript

Interpolation is a method of constructing new data from a given set of data points. In polynomial interpolation, we use a polynomial function to approximate a set of data points. Here is how you can implement polynomial interpolation in JavaScript:

index.tsx
// function to calculate the coefficients of the interpolating polynomial
function calculateCoefficients(x, y) {
  const n = x.length;
  const a = new Array(n).fill(0);

  for (let i = 0; i < n; i++) {
    let numerator = 1;
    let denominator = 1;

    for (let j = 0; j < n; j++) {
      if (i !== j) {
        numerator *= x[i] - x[j];
        denominator *= x[i] - x[j];
      }
    }

    a[i] = y[i] * numerator / denominator;
  }

  return a;
}

// function to evaluate the interpolating polynomial at a given point
function evaluatePolynomial(x, coeffs) {
  let result = 0;
  const n = coeffs.length;

  for (let i = 0; i < n; i++) {
    let term = coeffs[i];

    for (let j = 0; j < n; j++) {
      if (i !== j) {
        term *= (x - x[j]) / (x[i] - x[j]);  
      }
    }

    result += term;
  }

  return result;
}

// example usage
const x = [0, 1, 2, 3];
const y = [1, 4, 9, 16];
const coeffs = calculateCoefficients(x, y);
const yInterpolated = evaluatePolynomial(1.5, coeffs); // 5.5
1003 chars
48 lines

In this example, we first define a function calculateCoefficients that takes an array of x-values and a corresponding array of y-values, and returns the coefficients of the interpolating polynomial using the Lagrange formula. We then define a function evaluatePolynomial that takes a value of x and the coefficients of the interpolating polynomial, and returns the corresponding value of y.

To use these functions, you simply need to provide an array of x-values and a corresponding array of y-values, and then call calculateCoefficients to compute the coefficients of the interpolating polynomial. You can then call evaluatePolynomial to evaluate the interpolating polynomial at any point.

related categories

gistlibby LogSnag