9. Write a program to demonstrate Lagrange's interpolation formula.
/* program to execute Lagrange's interpolation */
#include <stdio.h>
#include < conio.h>
#define max 50
void main()
{
float arrx[max + 1], arry[max + 1], num, den, x, y = 0.0;
int i, j, n;
printf("Enter the value of n: ");
scanf("%d", &n);
printf("Enter value for x and y: \n"); /* Input data */
for (i = 0; i <= n; i++)
scanf("%f %f", &arrx[i], &arry[i]);
printf("\nEnter value of x for which value of y is needed: ");
scanf("%f", &x);
for (i = 0; i <= n; i++) /* Apply Interpolation Formula */
{
num = den = 1;
for (j = 0; j <= n; j++)
if (j != i)
{
num *= x - arrx[j];
den *= arrx[i] - arrx[j];
}
y += (num / den) * arry[i];
}
printf("Value of y = %f , when x = %f", y, x);
getch();
}
Output
Enter the value of n: 4
Enter values of x and y:
5 150
7 392
11 1452
13 2366
17 5202
Enter value of x for which value of y is needed: 9
Value of y = 809.999939, when x = 9.000000