Answer to Question #291176 in C++ for S bharath

Question #291176

Write a function Lagrange_interp which implements Lagrange interpolation to find data at an intermediate data point. Note: The degree of the polynomial will not be known to you unless the problem statement is given. The function should be able to deal with N data points. You can either use dynamic memory allocation for data storage in arrays or in a simpler approach, you may declare the array sizes as a large value.

1
Expert's answer
2022-01-27T07:46:52-0500
#include <iostream>
using namespace std;


double Lagrange_interp(double X[], double Y[], int n, double x) 
{
    double* L = new double[n];


    for (int j=0; j<n; j++) {
        L[j] = 1.0;
        for (int i=0; i<n; i++) {
            if (i != j) {
                L[j] *= (x - X[i])/(X[j] - X[i]);
            }
        }
    }


    double y = 0.0;
    for (int j=0; j<n; j++) {
        y += Y[j] * L[j];
    }


    delete [] L;
    return y;
}


int main() {
    int n;
    cout << "Enetr number of points: ";
    cin >> n;


    double *X = new double[n];
    double *Y = new double[n];


    for (int i=0; i<n; i++) {
        cout << "Enter " << i << "-th data (x, y): ";
        cin >> X[i] >> Y[i];
    }


    double x;
    cout << "Enter x ";
    cin >> x;
    cout << "Interpolated value at " << x << " is " 
         << Lagrange_interp(X, Y, n, x);
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment