Skip to main content

C program for Lagrange Interpolation

Lagrange Interpolation Example

#include<stdio.h>
#include<conio.h>

void main()
{
  float ax[100],ay[100],x,y=0,temp;
  int n,i,j;
 
  printf("Enter n: ");
  scanf("%d",&n);

  printf("Enter given data...");
  for(i=0;i<=n;i++)
  {
    printf("\nEnter x[%d] and y[%d]: ",i,i);
    scanf("%f%f",&ax[i],&ay[i]);
  }

  printf("Enter x: ");
  scanf("%f",&x);

  for(i=0;i<=n;i++)
  {
    temp=1;
    for(j=0;j<=n;j++)
    {
      if(j!=i)
      {
        temp*=(x-ax[j])/(ax[i]-ax[j]);
      }
    }
    y+=temp*ay[i];
  }
  printf("Hence, f(%f) = %f",x,y);
  getch();
}

Comments

Popular posts from this blog

C Program for Runge-Kutta-4 (RK-4) Method

Program for Runge-Kutta-4 (RK-4) Method #include <stdio.h> #include <conio.h> #include <math.h> float f(float x,float y) {   return ((y*y-x*x)/(y*y+x*x));   //y'=f(x,y)=equation } void main() {   float x0,y0,h,xn,yn;   printf("Enter x0 and y0: ");   scanf("%f%f",&x0,&y0); //y(x0)=y0   printf("Enter xn: ");   scanf("%f",&xn);   printf("Enter interval(h): ");   scanf("%f",&h);   do   {     float m1=f(x0,y0);     float m2=f(x0+h/2,y0+m1*h/2);     float m3=f(x0+h/2,y0+m2*h/2);     float m4=f(x0+h,y0+m3*h);     float m=(m1+2*m2+2*m3+m4)/6;     yn=y0+m*h;     //for next iteration         x0=x0+h;     y0=yn;   }while(x0<xn); printf("\n\nHence, y(%0.1f)=%0.4f",xn,yn); getch(); }