-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGeeksForGeeks-Newton's_Divided_Difference.cpp
78 lines (76 loc) · 1.8 KB
/
GeeksForGeeks-Newton's_Divided_Difference.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
70
71
72
73
74
75
76
77
78
// CPP program for implementing
// Newton divided difference formula
#include <bits/stdc++.h>
using namespace std;
// Function to find the product term
float proterm(int i, float value, float x[])
{
float pro = 1;
for (int j = 0; j < i; j++)
{
pro = pro * (value - x[j]);
}
return pro;
}
// Function for calculating
// divided difference table
void dividedDiffTable(float x[], float y[][10], int n)
{
for (int i = 1; i < n; i++)
{
for (int j = 0; j < n - i; j++)
{
y[j][i] = (y[j][i - 1] - y[j + 1]
[i - 1]) / (x[j] - x[i + j]);
}
}
}
// Function for applying Newton's
// divided difference formula
float applyFormula(float value, float x[],
float y[][10], int n)
{
float sum = y[0][0];
for (int i = 1; i < n; i++)
{
sum = sum + (proterm(i, value, x) * y[0][i]);
}
return sum;
}
// Function for displaying
// divided difference table
void printDiffTable(float y[][10],int n)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n - i; j++)
{
cout << setprecision(4) <<
y[i][j] << "\t ";
}
cout << "\n";
}
}
// Driver Function
int main()
{
// number of inputs given
int n = 4;
float value, sum, y[10][10];
float x[] = { 5, 6, 9, 11 };
// y[][] is used for divided difference
// table where y[][0] is used for input
y[0][0] = 12;
y[1][0] = 13;
y[2][0] = 14;
y[3][0] = 16;
// calculating divided difference table
dividedDiffTable(x, y, n);
// displaying divided difference table
printDiffTable(y,n);
// value to be interpolated
value = 7;
// printing the value
cout << "\nValue at " << value << " is " << applyFormula(value, x, y, n) << endl;
return 0;
}