33
Total Posts
3
Categories
24/7
Updated

C++

Write a program to find f(x) by using Lagrange Interpolation/ Newtonian Interpolation.

Published on Dec 22, 2025
#include <iostream>
using namespace std;

#define MAX 20

// -------- Lagrange Interpolation --------
double lagrange(double x[], double y[], int n, double xp) {
    double yp = 0.0;

    for (int i = 0; i < n; i++) {
        double term = y[i];
        for (int j = 0; j < n; j++) {
            if (j != i)
                term *= (xp - x[j]) / (x[i] - x[j]);
        }
        yp += term;
    }
    return yp;
}

// -------- Newton Forward Interpolation --------
double newtonForward(double x[], double y[][MAX], int n, double xp) {
    double h = x[1] - x[0];
    double p = (xp - x[0]) / h;
    double yp = y[0][0];

    double fact = 1, pterm = 1;
    for (int i = 1; i < n; i++) {
        fact *= i;
        pterm *= (p - (i - 1));
        yp += (pterm * y[0][i]) / fact;
    }
    return yp;
}

int main() {
    int n, choice;
    double x[MAX], y[MAX][MAX], xp;

    cout << "Enter number of data points: ";
    cin >> n;

    cout << "Enter x values:\n";
    for (int i = 0; i < n; i++)
        cin >> x[i];

    cout << "Enter corresponding y values:\n";
    for (int i = 0; i < n; i++)
        cin >> y[i][0];

    cout << "Enter value of x to find f(x): ";
    cin >> xp;

    cout << "\nChoose Method:\n";
    cout << "1. Lagrange Interpolation\n";
    cout << "2. Newton Forward Interpolation\n";
    cout << "Enter choice: ";
    cin >> choice;

    if (choice == 1) {
        double result = lagrange(x, y[0], n, xp);
        cout << "f(" << xp << ") = " << result << endl;
    }
    else if (choice == 2) {
        // Build forward difference table
        for (int j = 1; j < n; j++) {
            for (int i = 0; i < n - j; i++) {
                y[i][j] = y[i + 1][j - 1] - y[i][j - 1];
            }
        }

        double result = newtonForward(x, y, n, xp);
        cout << "f(" << xp << ") = " << result << endl;
    }
    else {
        cout << "Invalid choice!" << endl;
    }

    return 0;
}

Documentation

Input

Enter number of data points: 4
Enter x values:
1 2 3 4
Enter corresponding y values:
1 8 27 64
Enter value of x to find f(x): 2.5

Choose Method:
1. Lagrange Interpolation
2. Newton Forward Interpolation
Enter choice: 1

 

Output

f(2.5) = 15.625


Problem Setup

Given a set of data points (xi,yi), estimate f(x) for a given value of .

 

Important

  • Lagrange Interpolation

    • No difference table required

    • Works for unequal intervals

  • Newton Forward Interpolation

    • Requires equal intervals

    • Uses forward difference table

  • Both methods estimate f(x) from tabulated data