Newton Interpolation Forward C++


#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int fact(int k)
{
    int l,f=1;
    for(l=1;l<=k;l++)
    {
        f=f*l;
    }
    return f;
}
double f(int m,double p)
{
    int h;
    double pr=1.0,q;
    for(h=1;h<=m-1;h++)
    {
        pr=pr*(p-h);
    }
    q=p*pr;
    return q;
}
double b(int m,double p)
{
    int h;
    double pr=1.0,q;
    for(h=1;h<=m-1;h++)
    {
        pr=pr*(p+h);
    }
    q=p*pr;
    return q;
}

int main()
{
    double y[50][50],x[50];
    int n,i,j;
    double p,e,s,d,sum=0,r,sum1=0,r1;
    cout<<"Enter n="<<endl;
    cin>>n;
    cout<<"Starting Point="<<endl;
    cin>>s;
    cout<<"End Point="<<endl;
    cin>>e;
    cout<<"Difference="<<endl;
    cin>>d;
    p=(e-s)/d;
    cout<<"X"<<"\t"<<"Y"<<endl;
    for(i=0;i<n;i++)
    {
        cin>>x[i]>>y[0][i];
    }
     cout<<"X"<<"\t"<<"Y"<<endl;
    for(i=1;i<n;i++)
    {
        for(j=0;j<n-i;j++)
        {
            y[i][j]=y[i-1][j+1]-y[i-1][j];
        }
    }
    cout<<"Forward Difference Table"<<endl;
    for(j=0;j<n;j++)
    {
       printf("%lf",x[j]);
        for(i=0;i<n-j;i++)
        {
            printf("\t%lf",y[i][j]);
        }
        printf("\n");
    }
    for(i=2;i<=n-1;i++)
    {
        sum=sum+(f(i,p)/(fact(i)))*y[i][0];

    }
    r=y[0][0]+p*y[1][0]+sum;
    cout<<"Root is="<<r<<endl;

    cout<<"Backward Difference"<<endl;
    for(i=1;i<n;i++)
    {
        for(j=n-1;j>=i;j--)
        {
            y[i][j]=y[i-1][j]-y[i-1][j-1];
        }
    }
    for(j=0;j<n;j++)
    {
       printf("%lf",x[j]);
        for(i=0;i<=j;i++)
        {
            printf("\t%lf",y[i][j]);
        }
        printf("\n");
    }
     for(i=2;i<=n-1;i++)
    {
        sum1=sum1+(b(i,p)/(fact(i)))*y[i][i];

    }
    r1=y[n-1][n-1]+p*y[1][n-1]+sum1;
    cout<<"Root is="<<r1<<endl;







    return 0;
}

Download Coding Interview Book and Get More Tutorials for Coding and Interview Solution: Click Here

Download System Design Interview Book and Get More Tutorials and Interview Solution: Click Here

Do you need more Guidance or Help? Then Book 1:1 Quick Call with Me: Click Here

Share on Google Plus

About Ashadullah Shawon

I am Ashadullah Shawon. I am a Software Engineer. I studied Computer Science and Engineering (CSE) at RUET. I Like To Share Knowledge. Learn More: Click Here
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment