# Algorithm and C program for Lagrange interpolation

Share

### Algorithm

1. Start
2. Read the number of points (n)
3. Read the value of the spcefied point where interpolated value is to be find. (xpoint)
4. Read the data points
5. Calculate L[i] as:
for i=0 to i<n
for j=0 to j<n
if(i!=j)
L[i] = L[i] * ((x-x[j])/x[i]-x[j]))
end if
end for
end for
6. calculate interpolated value at xpoint as:
for i=0 to i<n
ivalue = ivalue + fx[i[+L[i]
end for
7. print the value of ivalue
8. stop

A complete C program:

``````
#include <stdio.h>

int main()
{
float x, fx, L,xpoint, ivalue=0;
int i,j,n;

printf("Enter the number of points: ");
scanf("%d",&n);

printf("Enter the value of point where interpolated value is to be obtained: ");
scanf("%f",&xpoint);

for(i=0;i<n;i++){
printf("%d. Enter the value of x and fx seprated by comma:",i+1);
scanf("%f,%f",&x[i],&fx[i]);
}

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

}
}

// calculating interpolated value at xpoint

for(i=0;i<n;i++){
ivalue += fx[i]*L[i];
}

printf("interpolated value at x=%f is %f",xpoint,ivalue);

return 0;
}``````
Share Healing