-
Notifications
You must be signed in to change notification settings - Fork 0
/
Newton_Forward_Interpolation.cpp
68 lines (62 loc) · 1.43 KB
/
Newton_Forward_Interpolation.cpp
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
#include <iostream>
using namespace std;
int factorial(int);
float calcU(float,float,float);
float calcP(int,float);
int main() {
int n;
cout<<"Enter no. of terms : ";
cin>>n;
float x, X[n], Y[n][n];
cout<<"\nEnter values of X : \n\n";
for (int i=0;i<n;i++) {
cout<<"Enter X"<<i<<" : ";
cin>>X[i];
}
cout<<"\nEnter values of Y : \n\n";
for (int i=0;i<n;i++) {
cout<<"Enter Y"<<i<<" : ";
cin>>Y[i][0];
}
cout<<"\nEnter 'x' for which 'y' is to be calculated : ";
cin>>x;
for (int i=1;i<n;i++) {
for (int j=0;j<n-i;j++) {
Y[j][i] = Y[j+1][i-1] - Y[j][i-1];
}
}
cout<<"\nForward Difference Table\n";
for(int i=0;i<n;i++) {
cout<<X[i]<<"\t";
for (int j=0;j<n-i;j++) {
cout<<Y[i][j]<<"\t";
}
cout<<endl;
}
float u = calcU(x,X[0],X[1]);
float summ = Y[0][0];
for (int i=1;i<n;i++) {
summ+=(calcP(i,u)*Y[0][i])/factorial(i);
//Y[0][i] is the first row of difference table
}
cout<<"\nInterpolated value of Y at X="<<x<<" is "<<summ;
cout<<endl;
return 0;
}
int factorial(int n) {
if (n<=1)
return 1;
return n*factorial(n-1);
}
float calcU(float x, float x0, float x1) {
return (x-x0)/(x1-x0);
}
float calcP(int i, float u) {
int j = 1;
float t=u;
while (j<i) {
t=t*(u-j);
j++;
}
return t;
}