-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathLagrange.c
44 lines (39 loc) · 1.06 KB
/
Lagrange.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// Polynomial interpolation using Lagrange's Method
#include <stdio.h>
#include <math.h>
#define MAX 15
int main()
{
int n;
float x[MAX], f[MAX], fp, lf, sum, xp;
char q = 'y';
printf("\nInput the number of data pairs: ");
scanf("%d", &n);
printf("\nInput data pairs x(i) and values f(i) (one set in each line): ");
for (int i = 0; i < n; i++)
{
scanf("%f %f", &x[i], &f[i]);
}
do
{
printf("\nInput x at which interpolation is required: ");
scanf("%f", &xp);
sum = 0.0;
for (int i = 0; i < n; i++)
{
lf = 1.0;
for (int j = 0; j < n; j++)
{
if (i != j)
lf = lf * (xp - x[j]) / (x[i] - x[j]);
}
sum += lf * f[i];
}
fp = sum;
printf("\nInterpolated function value at x = %.5f is %.5f.\n", xp, fp);
printf("Do you want to input another value? (y/n): ");
fflush(stdin); // clear input buffer
scanf("%c", &q);
} while (q == 'y');
return 0;
}