The Lagrange polynomial

67 views Asked by At

My program

#include <iostream>
#include <vector>

using namespace std;

string lagrange(vector<pair<double, double>>& points) {
    int n = points.size();
    string result = "";

    for (int i = 0; i < n; i++) {
        string term = to_string(points[i].second);
        for (int j = 0; j < n; j++) {
            if (j != i) {
                term += " * (x - " + to_string(points[j].first) + ") / (" + to_string(points[i].first - points[j].first) + ")";
            }
        }
        if (i < n - 1) {
            term += " +";
        }
        result += term;
    }

    return result;
}

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

    vector<pair<double, double>> points;
    cout << "Enter the dots in the format x y:\n";
    for (int i = 0; i < n; i++) {
        double x, y;
        cin >> x >> y;
        points.push_back(make_pair(x, y));
    }

    string result = lagrange(points);
    cout << "The Lagrange polynomial for the introduced points:\n" << result << endl;

    return 0;
}

How to derive the Lagrange polynomial in the form of a polynomial? That is, not (x - x1) * (x - x2) * ... (x - xi), but in the form a1 * x^n + a2 * x^n-1+ ... + an

0

There are 0 answers