Write a program that does the following: Reads the input data set from file name
ID: 3571578 • Letter: W
Question
Write a program that does the following: Reads the input data set from file named "data.txt". Assume that the input file contains x and y values as shown in the sample to the right (the first number in each line is the x value). The number of data points in the input file is not known but assume that they will not exceed 100. Once it gets the data in two one-dimensional arrays (x and y), it applies the curve fitting methodology in order to find the least-squares line that best fits the input data set by calculating the slope m and intercept c as follows: m = (sigma xy) - (sigma x)y bar/(sigma x^2) - (sigma x)x bar c = y bar - mx bar sigma x is the sum of the x values; sigma x^2 is the sum of the squares of the x values; sigma xy is the sum of the products of the corresponding x and y values; x bar is the mean (average) of the x values; y bar is the mean (average) of the y values.Explanation / Answer
Hii there I have tried my best to write the program for the same .I guess this may help you out.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
ifstream myfile;
int n;
double x[n],y[n];
myfile.open("data.txt");
cout << "Enter the no of data points to be entered (let it be less than 100) : ";
cin >> n ;
if (myfile.is_open())
{
for ( int i = 0 ; i < n ; ++i)
{
myfile >> x[i]; // will store all the values of x from "data.txt";
myfile >> y[i]; //will store all the values of y from "dat.txt";
}
}
double xsum = 0 , x2sum =0 , ysum=0 , xysum = 0 ;
for (i=0 ; i<n ; i++)
{
xsum = xsum + x[i]; //calculate sigma x as the sum of x values
ysum = ysum +y[i]; //calculate sigma y as the sum of y values
x2sum = x2sum + pow(x[i] , 2); //calculate sum of the squares of the x values
xysum = xysum + x[i] * y[i]; //calculate the sum of the products of the corresponding x and y values
}
avg1= xsum/n; //calculate average of x values
avg2 =ysum/n; //calculate average of y values
m = ((xysum) - (xsum*avg1)) / ((x2sum) - (xsum*avg2)) ; // calculates slope m
c = (avg2 - (m.avg1)); // calculates intercept c
cout << " The slope of the given set of values is : "<< m << endl;
cout << " The intercept of the given set of values is : " << c <<endl;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.