Forward Backward
Forward Backward
#include<iomanip>
#include<math.h>
#include<stdlib.h>
using namespace std;
float cal(float u, int n)
{
float temp = u;
for (int i = 1; i < n; i++)
temp = temp * (u - i);
return temp;
}
float cal2(float v,int n)
{
float temp2 = v;
for (int i=1;i<n;i++)
temp2=temp2*(v+i);
return temp2;
}
int fact(int n)
{
int f = 1;
for (int i = 2; i <= n; i++)
f *= i;
return f;
}
int main()
{
int n,i,j,k;
float h,b,x0;
cout<<"How many Data points you want to enter?\n\tn: ";cin>>n;
float x[i],y[n][n];
cout<<"USE the values of x such that there is a FIXED STEPSIZE."<<endl;
cout<<"\nThe stepsize for x values:\t";cin>>h;
cout<<"The First x value is:\t";cin>>x0;
cout<<"\nEnter the x value and corresponding y value: "<<endl;
for (i=0;i<n;i++)
{ x[i]=x0+i*h;
cout<<"\n\tx["<<i<<"]="<<x[i];
cout<<"\ty["<<i<<"]=";cin>>y[i][0];
}
cout<<"\n\nGive the point for interpolation :\t";cin>>b;
if (x[0]<=b && b<=x[n/2])
{
cout<<"\n\n\tHere We will use Newton Forward interpolation. \n\n";
for (i=1;i<n;i++)
{
for (j=0;j<=n-i;j++)
{
y[j][i]=y[j+1][i-1]-y[j][i-1];
}
}
cout<<"\tForward Difference Table for the given Data is : "<<endl;
for (i=0;i<n;i++)
{
cout<<x[i];
for(j=0;j<n-i;j++)
{
cout<<setw(10)<<y[i][j]<<setw(10)<<"\t";
}
cout<<endl;
}
cout << "\nThe Value at " << b << " using Newton Forward interpolation method is : " << sum << endl;
}
else if (x[n/2]<=b && b<=x[n-1])
{cout<<"\n\n\tHere we will use the Newton Backward Interpolation .\n\n";
for(i=1;i<n;i++)
{
for(j=n-1;j>i-1;j--)
{
y[j][i] = y[j][i-1] - y[j-1][i-1];
}
}
cout<<endl<<" THE BACKWARD DIFFERENCE TABLE IS:- \n" << endl;
for(i=0;i<n; i++)
{
cout<<x[i]<<"\t";
for(j=0;j<=i;j++)
{
cout << setw(6)<< y[i][j]<<setw(6)<<"\t";
}
cout << endl;
}
float sum = y[n-1][0];
float v = (b - x[n-1]) / (x[1] - x[0]);
for (int i = 1; i < n; i++)
{
sum = sum + (cal2(v, i) * y[n-1][i]) /fact(i);
}
cout << "\n Value at " << b << " using Newton backward interpolation is " << sum << endl;
}
return 0;
}