To implement newtons forward and backward interpolation formula using C ! !

 code: 

#include <stdio.h>

// Function to calculate the factorial of a number
int factorial(int n) {
  int result = 1;
  for (int i = 1; i <= n; i++) {
    result *= i;
  }
  return result;
}

// Function to calculate the divided difference table
void calculateDividedDifferenceTable(double x[], double y[], int n, double f[][n]) {
  // Initialize the divided differences with y values
  for (int i = 0; i < n; i++) {
    f[i][0] = y[i];
  }

  // Calculate the divided differences
  for (int j = 1; j < n; j++) {
    for (int i = 0; i < n - j; i++) {
      f[i][j] = (f[i + 1][j - 1] - f[i][j - 1]) / (x[i + j] - x[i]);
    }
  }
}

// Function to interpolate using Newton's forward interpolation formula
double newtonForwardInterpolation(double x[], double f[][n], int n, double value) {
  // Calculate the u value
  double u = (value - x[0]) / (x[1] - x[0]);

  // Calculate the interpolated value
  double sum = f[0][0];
  for (int i = 1; i < n; i++) {
    sum += u_cal(u, i) * f[0][i] / factorial(i);
  }

  return sum;
}

// Function to interpolate using Newton's backward interpolation formula
double newtonBackwardInterpolation(double x[], double f[][n], int n, double value) {
  // Calculate the u value
  double u = (value - x[n - 1]) / (x[n - 1] - x[n - 2]);

  // Calculate the interpolated value
  double sum = f[n - 1][0];
  for (int i = 1; i < n; i++) {
    sum += u_cal(u, i) * f[n - 1][i] / factorial(i);
  }

  return sum;
}

// Function to calculate u mentioned in the formula
double u_cal(double u, int n) {
  double temp = u;
  for (int i = 1; i < n; i++) {
    temp *= (u + i);
  }
  return temp;
}

int main() {
  // Number of data points
  int n = 4;

  // x and y values
  double x[] = {1, 2, 3, 4};
  double y[] = {1, 4, 9, 16};

  // Divided difference table
  double f[n][n];

  // Calculate the divided difference table
  calculateDividedDifferenceTable(x, y, n, f);

  // Value to interpolate at
  double value = 2.5;

  // Interpolated value using Newton's forward interpolation formula
  double interpolatedValueForward = newtonForwardInterpolation(x, f, n, value);

  // Interpolated value using Newton's backward interpolation formula
  double interpolatedValueBackward = newtonBackwardInterpolation(x, f, n, value);

  // Print the interpolated values
  printf("Interpolated value using Newton's forward interpolation formula: %lf\n", interpolatedValueForward);
  printf("Interpolated value using Newton's backward interpolation formula: %lf\n", interpolatedValueBackward);

  return 0;
}

Comments

Popular Posts