Write youThe dataset in the file “linedat.txt” contains two columns and it can be described by a linear
function of the form y = ax + b. The x -value is represented by the first column and the y-value
by the second column. Write a C++ program containing a function lsqfit() that performs a
least-squares fit to the data and returns the values of a and b with their standard deviations as
well as the correlation coefficient R2. (18 marks)
[Hint: to read the data from the file into two arrays one representing X[len] and another
Y [len] (with len indicating length of the array) use the following code fragment:
1 ve c tor<double> X, Y;
double vecx , vecy ;
3
i f s t r e am i n f i l e ( ” l i n e d a t a . txt ” ) ;
5
whi l e ( i n f i l e >> vecx >> vecy ){
7 X. push back ( vecx ) ;
Y. push back ( vecy ) ;
9 }
You must include the fstream & vector preprocessor directives before using them.]r question here.
R2 is not itself a correlation coefficient (in general, it's one minus the normalised squared error in the approximation - which may or may not be linear - but in the linear case it does work out as the square of the correlation coefficient, as @againtry points out below), so you need your lecturer to clarify. It's also meaningless to talk about the standard deviations of a and b, since you only have one value of each.
No. of records: 101
mean_x = 50
mean_y = 147.788
Least squares best fit is y = 2.99625x + -2.02447
(y is the weekly balance and x is the week number)
Std dev'n x: 29.1548
Std dev'n y: 87.3781
Correlation: 0.999735 ( see https://www.mathsisfun.com/data/correlation.html
- which is R and not R^2, so if required answer is R^2 then square it.)
Program ended with exit code: 0