Lagrange's Interpolation

Submitted by Karthikeyan on

Sample C Program that uses Lagrange's interpolation formulae in mathematics


#include 
#include 
line()
{
	int i;
	printf("\n");
	for(i=0; i<60; i++)
	printf("*");
}
main()
{
	float x[100], f[100], xin, sum, prod;
	int i, n, j;
	printf("\n\t Lagrange's Interpolation ");
	printf("\n\t *************************");
	printf("\n\t Enter the values of xin[f(x)], n [No. of pairs]:\n");
	scanf("%f%d", &xin, &n);
	printf("\t\t xin=%f\t\t n=%d\t\t", xin, n);
	printf("\nEnter the x, y values [pairs]\n");
	for(i=1; i<=n; i++)
	{
	   scanf("%f%f", &x[i], &f[i]);
    }
    line();
    printf("\n\t\t x[i]\t\t\tf[i]\n");
    line();
	for(i=1; i<=n; i++)
	{
		printf("\n\t\t%f\t\t\t%f\n", x[i], f[i]);
	}
	sum = 0.0;
	for(i=1; i<=n; i++)
	{
		prod = 1.0;
		for(j=1; j<=n; j++)
		{
			if(j != i)
			{
			prod = prod*(xin - x[j]) / (x[i] - x[j]);
			}
		}
		sum = sum + prod*f[i];
	}
	line();
	printf("\n\n\t\t\t sum = %10.4f\n", sum);
	line();
}