Example:
Lagrange's formula:
Here x=9
Therefore :
After evaluation :
P(9) = -16.66+209.06+1290.66-788.66+115.60 = 810
Code:
#include<stdio.h>
void main()
{ float x[10],y[10],xx,nr,dr,li=0;
int i,j,n;
printf("\nEnter the no of data:");
scanf("%d",&n);
for(i=0;i<n;i++)
{ printf("\nx%d:",i+1);
scanf("%f",&x[i]);
printf("\ny%d:",i+1);
scanf("%f",&y[i]);
}
printf("\nEnter the value of x");
scanf("%f",&xx);
printf("\nX\tY=f(x)");
for(i=0;i<n;i++)
{ printf("\n%.2f\t%.2f",x[i],y[i]);
}
for(i=0;i<n;i++)
{ nr=dr=1;
for(j=0;j<n;j++)
{ if(i!=j)
{ nr=nr*(xx-x[j]);
dr=dr*(x[i]-x[j]);
}
}
li=li+(nr/dr)*y[i];
}
printf("\nvalue of function P(x) at x=%.2f is %.2f",xx,li);
}
Evaluate P(9) using Lagrange’s formula for the following data:
X
|
5
|
7
|
11
|
13
|
17
|
Y
|
150
|
392
|
1452
|
2366
|
5202
|
Solution:
Here x=9
Therefore :
After evaluation :
P(9) = -16.66+209.06+1290.66-788.66+115.60 = 810
Code:
#include<stdio.h>
void main()
{ float x[10],y[10],xx,nr,dr,li=0;
int i,j,n;
printf("\nEnter the no of data:");
scanf("%d",&n);
for(i=0;i<n;i++)
{ printf("\nx%d:",i+1);
scanf("%f",&x[i]);
printf("\ny%d:",i+1);
scanf("%f",&y[i]);
}
printf("\nEnter the value of x");
scanf("%f",&xx);
printf("\nX\tY=f(x)");
for(i=0;i<n;i++)
{ printf("\n%.2f\t%.2f",x[i],y[i]);
}
for(i=0;i<n;i++)
{ nr=dr=1;
for(j=0;j<n;j++)
{ if(i!=j)
{ nr=nr*(xx-x[j]);
dr=dr*(x[i]-x[j]);
}
}
li=li+(nr/dr)*y[i];
}
printf("\nvalue of function P(x) at x=%.2f is %.2f",xx,li);
}
Output:
Enter the no of data:5
x1:5 y1:150
x2:7 y2:392
x3:11 y3:1452
x4:13 y4:2366
x5:17 y5:5202
Enter the value of x 9
X Y=f(x)
5.00 150.00
7.00 392.00
11.00 1452.00
13.00 2366.00
17.00 5202.00
value of function P(x) at=9.00 is 810.00
No comments:
Post a Comment