fork download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <vector>
  4. #include <cmath>
  5. #include <string>
  6.  
  7. using namespace std;
  8.  
  9. void newton_forward_interpolation() {
  10. int n = 4;
  11. double x_vals[] = {0.0, 1.0, 2.0, 3.0};
  12. double y_vals[] = {1.0, 0.0, 1.0, 10.0};
  13. double a = 0.5;
  14.  
  15. vector<vector<double>> diff_table(n, vector<double>(n));
  16.  
  17.  
  18. for (int i = 0; i < n; ++i) {
  19. diff_table[i][0] = y_vals[i];
  20. }
  21.  
  22.  
  23. for (int j = 1; j < n; ++j) {
  24. for (int i = 0; i < n - j; ++i) {
  25. diff_table[i][j] = diff_table[i + 1][j - 1] - diff_table[i][j - 1];
  26. }
  27. }
  28.  
  29.  
  30. cout << setprecision(6) << fixed;
  31. cout << "--- Newton's Forward Interpolation ---" << endl;
  32. cout << "Input table (x, y):" << endl;
  33. for (int i = 0; i < n; ++i) {
  34. cout << "(" << x_vals[i] << ", " << y_vals[i] << ") ";
  35. }
  36. cout << "\nPoint of Interpolation (a): " << a << endl;
  37. cout << string(60, '-') << endl;
  38.  
  39.  
  40. cout << "Output: The forward difference table is:" << endl;
  41. cout << setw(10) << "x" << setw(10) << "y";
  42. for (int j = 1; j < n; ++j) {
  43. cout << setw(10) << "Del^" << j << "y";
  44. }
  45. cout << endl;
  46. cout << string(10 + 10 * n, '-') << endl;
  47.  
  48. for (int i = 0; i < n; ++i) {
  49. cout << setw(10) << x_vals[i] << setw(10) << diff_table[i][0];
  50. for (int j = 1; j < n - i; ++j) {
  51. cout << setw(10) << diff_table[i][j];
  52. }
  53. cout << endl;
  54. }
  55. cout << string(10 + 10 * n, '-') << endl;
  56.  
  57.  
  58. double h = x_vals[1] - x_vals[0];
  59. double u = (a - x_vals[0]) / h;
  60. double sum = diff_table[0][0];
  61. double p = 1.0;
  62.  
  63. for (int j = 1; j < n; ++j) {
  64. p = p * (u - j + 1) / j;
  65. sum = sum + p * diff_table[0][j];
  66. }
  67.  
  68.  
  69. cout << "\nThe value of y at x=" << a << " is " << round(sum * 1000.0) / 1000.0 << endl;
  70. cout << "Calculated value: " << sum << endl;
  71. }
  72.  
  73. int main() {
  74. newton_forward_interpolation();
  75. return 0;
  76. }
Success #stdin #stdout 0.01s 5320KB
stdin
Standard input is empty
stdout
--- Newton's Forward Interpolation ---
Input table (x, y):
(0.000000, 1.000000) (1.000000, 0.000000) (2.000000, 1.000000) (3.000000, 10.000000) 
Point of Interpolation (a): 0.500000
------------------------------------------------------------
Output: The forward difference table is:
         x         y      Del^1y      Del^2y      Del^3y
--------------------------------------------------
  0.000000  1.000000 -1.000000  2.000000  6.000000
  1.000000  0.000000  1.000000  8.000000
  2.000000  1.000000  9.000000
  3.000000 10.000000
--------------------------------------------------

The value of y at x=0.500000 is 0.625000
Calculated value: 0.625000