#include <iostream>
#include <iomanip>
#include <vector>
#include <cmath>
#include <string>
using namespace std;
void newton_backward_interpolation() {
int n = 4;
double x_vals[] = {0.0, 1.0, 2.0, 3.0};
double y_vals[] = {1.0, 0.0, 1.0, 10.0};
double a = 0.5;
vector<vector<double>> diff_table(n, vector<double>(n));
for (int i = 0; i < n; ++i) {
diff_table[i][0] = y_vals[i];
}
for (int j = 1; j < n; ++j) {
for (int i = 0; i < n - j; ++i) {
diff_table[i][j] = diff_table[i + 1][j - 1] - diff_table[i][j - 1];
}
}
cout << setprecision(6) << fixed;
cout << "--- Newton's Backward Interpolation ---" << endl;
cout << "Input table (x, y):" << endl;
for (int i = 0; i < n; ++i) {
cout << "(" << x_vals[i] << ", " << y_vals[i] << ") ";
}
cout << "\nPoint of Interpolation (a): " << a << endl;
cout << string(60, '-') << endl;
cout << "Output: The backward difference table is (same as forward, but values used start at the bottom):" << endl;
cout << setw(10) << "x" << setw(10) << "y";
for (int j = 1; j < n; ++j) {
cout << setw(10) << "Nabla^" << j << "y";
}
cout << endl;
cout << string(10 + 10 * n, '-') << endl;
for (int i = 0; i < n; ++i) {
cout << setw(10) << x_vals[i] << setw(10) << diff_table[i][0];
for (int j = 1; j < n - i; ++j) {
cout << setw(10) << diff_table[i][j];
}
cout << endl;
}
cout << string(10 + 10 * n, '-') << endl;
double h = x_vals[1] - x_vals[0];
double u = (a - x_vals[n - 1]) / h;
double sum = diff_table[n - 1][0];
double p = 1.0;
for (int j = 1; j < n; ++j) {
double backward_diff = diff_table[n - 1 - j][j];
p = p * (u + j - 1) / j;
sum = sum + p * backward_diff;
}
cout << "\nThe value of y at x=" << a << " is " << round(sum * 1000.0) / 1000.0 << endl;
cout << "Calculated value: " << sum << endl;
}
int main() {
newton_backward_interpolation();
return 0;
}