Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- class PolynomialFit
- {
- int i,j,k,n,N;
- double *x,*y;
- public:
- void GaussEM(double B[][4],double a[]);
- void GetData();
- void Method();
- };
- void PolynomialFit::GetData()
- {
- freopen("data.txt","r",stdin);
- cout<<"Enter the number of data of each variable"<<endl;
- cin>>N;
- x = new double[N];
- y = new double[N];
- cout<<"Enter all value of X : "<<endl;
- for (i=0;i<N;i++)
- cin>>x[i];
- cout<<"Enter the all value of Y : "<<endl;
- for (i=0;i<N;i++)
- cin>>y[i];
- cout<<"Enter the degree of the equation :"<<endl;
- cin>>n;
- }
- void PolynomialFit::Method()
- {
- double X[2*n+1];
- for (i=0;i<2*n+1;i++)
- {
- X[i]=0;
- for (j=0;j<N;j++)
- X[i]=X[i]+pow(x[j],i);
- }
- double B [3][4];
- double a[3];
- for (i=0;i<=n;i++)
- for (j=0;j<=n;j++)
- B[i][j]=X[i+j];
- double Y[n+1];
- for (i=0;i<n+1;i++)
- {
- Y[i]=0;
- for (j=0;j<N;j++)
- Y[i]=Y[i]+pow(x[j],i)*y[j];
- }
- for (i=0;i<=n;i++)
- B[i][n+1]=Y[i];
- n=n+1;
- GaussEM(B,a);
- cout<<"All Coefficient are below:\n";
- for (i=0;i<n;i++)
- cout<<"x^"<<i<<"="<<a[i]<<endl;
- cout<<"Final Equation is"<<endl;
- for (i=0;i<n;i++)
- cout<<"+"<<a[i]<<""<<"x^"<<i;
- cout<<endl;
- }
- void PolynomialFit::GaussEM(double B[][4],double a[])
- {
- for (i=0;i<n;i++)
- for (k=i+1;k<n;k++)
- if (B[i][i]<B[k][i])
- for (j=0;j<=n;j++)
- {
- double temp=B[i][j];
- B[i][j]=B[k][j];
- B[k][j]=temp;
- }
- for (i=0;i<n-1;i++)
- for (k=i+1;k<n;k++)
- {
- double t=B[k][i]/B[i][i];
- for (j=0;j<=n;j++)
- B[k][j]=B[k][j]-t*B[i][j];
- }
- for (i=n-1;i>=0;i--)
- {
- a[i]=B[i][n];
- for (j=0;j<n;j++)
- if (j!=i)
- a[i]=a[i]-B[i][j]*a[j];
- a[i]=a[i]/B[i][i];
- }
- }
- int main()
- {
- PolynomialFit ob;
- ob.GetData();
- ob.Method();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement