'Miscalculation of Lagrange interpolation formula for higher degree

I am approximating Runge’s function using Lagrange’s interpolation formula for 50 interpolation points. I have written the following program to do this, but I am getting the wrong value for x= -0.992008. That wrong value is 4817543.091313, but it should be 5197172.55933613. I have got this value from the following link: Link The code used are as follows:

#include <stdio.h>
#include <math.h>

double
runge(double x)
{
    return (1 / (1 + (25 * x * x)));
}

double
ab(double x)
{
    if (x < 0)
        return -1 * x;
    return x;
}

double
lag_func(double x, double *y_i, double *x_i, int n)
{
    double ex = 0.0;

    for (int i = 0; i <= n; i++) {
        double numer = 1.0,
            denom = 1.0,
            prod = 1.0;

        for (int j = 0; j <= n; j++) {
            if (i != j) {
                numer = (x - x_i[j]);
                denom = (x_i[i] - x_i[j]);
                prod *= numer / denom;
            }
        }
        ex += (prod) * y_i[i];
    }
    return ex;
}

int
main()
{
    int n;

    scanf("%d", &n);
    double y_i[n + 1],
     x_i[n + 1];

    for (int i = 0; i < n + 1; i++) {
        x_i[i] = ((2 * (double) i) / (double) n) - 1;
        y_i[i] = runge(x_i[i]);
    }

    printf("%lf\n", lag_func(-0.992008, y_i, x_i, n));
    return 0;
}


Solution 1:[1]

The web site is rounding its Runge coefficients to six digits. Given the magnitudes of the terms involved, up to 3.9978•1011, this introduces multiple errors up to around 2•105.

This can be seen by inserting y_i[i] = round(y_i[i] * 1e6) / 1e6; after y_i[i] = runge(x_i[i]);. Then the output of the program is 5197172.558199, matching the web site’s inaccurate result.

The web site is wrong; the result of the code in the question is better.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1