-
Notifications
You must be signed in to change notification settings - Fork 0
/
Newton Backward Interpolation
69 lines (59 loc) · 1.38 KB
/
Newton Backward Interpolation
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <stdio.h>
// Calculation of u mentioned in formula
float u_cal(float u, int n)
{
float temp = u;
for (int i = 1; i < n; i++)
temp = temp * (u + i);
return temp;
}
// Calculating factorial of given n
int fact(int n)
{
int f = 1;
for (int i = 2; i <= n; i++)
f *= i;
return f;
}
int main()
{
int n;
printf("Enter the number of values: ");
scanf("%d", &n);
int x[n];
printf("Enter the values of x: ");
for(int i = 0; i < n; i++)
{
scanf("%d", &x[i]);
}
// y[][] is used for difference table with y[][0] used for input
float y[n][n];
printf("Enter the values of y: ");
for(int i = 0; i < n; i++)
{
scanf("%f", &y[i][0]);
}
// Value to interpolate at
float value;
printf("Enter the value to evaluate at: ");
scanf("%f", &value);
// Calculating the backward difference table
for (int i = 1; i < n; i++) {
for (int j = n - 1; j >= i; j--)
y[j][i] = y[j][i - 1] - y[j - 1][i - 1];
}
// Displaying the backward difference table
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++)
printf("%f \t", y[i][j]);
printf("\n");
}
// Initializing u and sum
float sum = y[n - 1][0];
float u = (value - x[n - 1]) / (x[1] - x[0]); // (x - xn)/h
for (int i = 1; i < n; i++) {
sum = sum + (u_cal(u, i) * y[n - 1][i]) / fact(i);
}
printf("Value at %f is: %f\n", value, sum);
return 0;
}