In this project, you must read the x - and y -coordinate pairs in from a data fi
ID: 3560317 • Letter: I
Question
In this project, you must read the x- and y-coordinate pairs in from a data file of unknown length. Each line in the file must contain both coordinates, separated by whitespace. In addition, you must use functions in this project, splitting the work up into smaller components and reinforcing your skills with parameter passing and arrays.
You are required to create the following functions, and you must list them in this order above the main program (no prototypes, please!):
Number (for reference)
Role
Method
Number (for reference)
Role
Method
Explanation / Answer
#include<iostream>
#include<fstream>
using namespace std;
void Input(double x[],double y[],int &size)
{
ifstream infile("input.txt");
int i=0;
while(!infile.eof())
{
infile >> x[i] >> y[i];
i++;
}
size = i;
}
double sample_mean(double x[],int size)
{
double sum = 0;
for(int i=0; i<size; i++)
sum = sum + x[i];
return sum/size;
}
double deviation(double x[],int size,double sample_mean)
{
double sum = 0;
for(int i=0; i<size; i++)
sum = sum + ((x[i] - sample_mean)*(x[i] - sample_mean));
return sum/size;
}
double compute_correlation_coefficient(double x[],double y[],int size)
{
double sum_xy = 0;
double sum_x = 0;
double sum_x_s = 0;
double sum_y = 0;
double sum_y_s = 0;
double final = 0;
for(int i=0; i<size; i++)
{
sum_xy = sum_xy + x[i]*y[i];
sum_x = sum_x + x[i];
sum_x_s = sum_x_s + x[i]*x[i];
sum_y = sum_y + y[i];
sum_y_s = sum_y_s + x[i]*x[i];
}
for(int i=0; i<size; i++)
{
final = final + (((x[i]-sample_mean(x,size))/deviation(x,size,sample_mean(x,size)))*((y[i]-sample_mean(y,size))/deviation(y,size,sample_mean(y,size))));
}
final = final/(size-1);
return (final*deviation(y,size,sample_mean(y,size)))/deviation(x,size,sample_mean(x,size));
}
double compute_line(double x[],double y[],int size)
{
double sum_y = 0;
double sum_x = 0;
for(int i=0; i<size; i++)
{
sum_y = sum_y + y[i];
sum_x = sum_x + x[i];
}
return sample_mean(y,size) - compute_correlation_coefficient(x,y,size)*sample_mean(x,size);
}
void print_line(double y_intercept, double slope)
{
cout <<"Regression line: y = " << y_intercept << " + " << slope << "x" << endl;
}
int main(int argc,char *argv[])
{
double x[100];
double y[100];
int size;
Input(x,y,size);
print_line(compute_line(x,y,size),compute_correlation_coefficient(x,y,size));
system("pause");
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.