-
Notifications
You must be signed in to change notification settings - Fork 0
/
Newton_Backward_Interpolation.cpp
69 lines (62 loc) · 1.44 KB
/
Newton_Backward_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
69
#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=n-1;j>=i;j--) {
Y[j][i] = Y[j][i-1] - Y[j-1][i-1];
}
}
cout<<"\nBackward Difference Table\n";
for(int i=0;i<n;i++) {
cout<<X[i]<<"\t";
for (int j=0;j<=i;j++) {
cout<<Y[i][j]<<"\t";
}
cout<<endl;
}
float u = calcU(x,X[n-1],X[n-2]);
float summ = Y[n-1][0];
for (int i=1;i<n;i++) {
summ+=(calcP(i,u)*Y[n-1][i])/factorial(i);
//Y[n-1][i] is the last 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 xn, float xn1) {
return (x-xn)/(xn-xn1);
}
float calcP(int i, float u) {
int j = 1;
float t=u;
while (j<i) {
t=t*(u+j);
j++;
}
return t;
}