|
//A program finds the best-fitted straight line to the x and y values, and then writes
//the original x, y values and the new y values on the line (for each x) to a data file.
#include<iostream>; //include the first library
#include<fstream>; //include the fstream library
using namespace std; //tell complier that we will use entire namespace standard
void main(void)
{
double ax,ay; //declare two double variables
double x[20]={1.0000,2.0000,3.0000,4.0000,5.0000,6.0000,7.0000,8.0000,9.0000,10.0000,11.0000,12.0000,13.0000,14.0000,15.0000,16.0000,17.0000,18.0000,19.0000,20.0000};
//declare a double array with length 20 to store original x values
double y[20]={13.3068,15.0928,16.2509,18.6416,23.6987,27.6380,26.1267,28.4638,33.9061,35.6735,36.0599,39.9298,40.6010,40.0202,43.9743,43.4650,45.7730,50.0811,51.1671,52.4696};
//declare a double array with length 20 to store original y values
double sumx=0, sumy=0; //declare two double variables
double sub1=0, sub2=0, sumsub1=0, sumsub2=0;
//declare four double variables
double a,b; //declare two double variables
for(int i=0;i<20;i++) //set a for loop to calculate the sum of original x values
//and the sum of original y values
{
sumx=sumx+x[i];
sumy=sumy+y[i];
}
ax=sumx/20; //calculate the average of x values
ay=sumy/20; //calculate the average of y values
cout<<"The average value of X is:"<<ax<<"\nThe average value of Y is:"<<ay;
//Display the average of all x values and y values
for(int j=0;j<20;j++) //set a for loop to calculate the component
//of equation of linear regression to get the value of slope
{
sub1=(x[j]-ax)*(y[j]-ay);
sub2=(x[j]-ax)*(x[j]-ax);
sumsub1=sumsub1+sub1;
sumsub2=sumsub2+sub2;
}
a=sumsub1/sumsub2; //the equation to calculate the slope
//by using the value get from the last for loop
b=ay-a*ax; //calculate the value of constant b
cout<<"\nThe value of slope 'a' is:"<<a<<"\nThe value of 'b' is:"<<b;
//display the value of slope a and the value of constant b
ofstream out("data.dat");//opening a file and output the value of original
//x, y and new y to a data file named "data.dat"
out<<"x"<<"\t\t"<<"y"<<"\t\t"<<"new y"<<endl;
//set the format of values display in data file
for(int k=0;k<20;k++) //set a for loop to display
//the value of x, y and calculated new y
{
out<<x[k]<<"\t\t"<<y[k]<<"\t\t"<<a*x[k]+b<<endl;
}
cout<<"\nThe data is output to the file\n";
//indicate the data is stored in the data file
system("pause"); //keep the screen otherwise it will appear fast
}
|
|