Weighted line of best fit

New to programming in C++, should be relatively straightforward for most of you guys.

I have a file of 3 columns of data; x,y,z(sigma)

My program reads the file and spits the data back out onto the screen.

However I want it to give the weighted line of best fit, and the chi squared value.

I have been given this:

If Sw(x) means the weighted sum over all the points of the x values:



i.e. Sw(x) = S(w*x)(and S(x) means the sum over all of the x values)where w, the weight for each point, is given by w = 1 / (sigma)^2

Then if the sum of the weights is Sw(1) (= S(w)), and D is given by
D = ( Sw(1) * Sw(x^2) - (Sw(x))^2 )then the line of best fit parameters, the gradient m +/- dm and intercept c +/- dc are given by
m = ( Sw(1) * Sw(x*y) - Sw(x) * Sw(y) ) / D dm = sqrt( Sw(1) / D ) c = ( Sw(y) * Sw(x^2) - Sw(x) * Sw(x*y) ) / D dc = sqrt( Sw(x^2) /D )

The chi-squared value is given by xsq = Sw(( m*x + c - y )^2)where (m*x + c - y)/sigma is the residual for each point, and sigma is the error on each y value.

If you need the current code I have written I will upload it

Thanks in advance!
Could you post what you have done so far please?

If the code is too long use pastebin and just give us the link.
// LineFit
// Reads in a file of x, y, sigma data points from "xys_data.txt"
// and computes the weighted line of best fit through them


// Includes and header
#include <iostream>
#include <fstream>

using namespace std;


// Define our structure for the data points
// Sigma = z
struct dataPoint
{

double x;
double y;
double z;
double Sw;
double m;
double c;
double w;

};



// main program
int main() {

// Declare variables
int i = 0;
dataPoint myPoints[11]; //Creates an array dataPoint structures

// Open the file
ifstream myFile ("xys_data.txt");

if(myFile.is_open()) {
// So file is open for reading
cout << "Succesfully opened the file!\n";

while( !myFile.eof() ) {
// Read a line
myFile >> myPoints[i].x >> myPoints[i].y >> myPoints[i].z;
// Increment the array index counter
i++;
}


} else {
cout << "Unable to open the file!\n";
exit(1);
}
// compute the line of best fit





// compute chi-squared





// output results to screen
for ( int i = 0; i < 11; i++ ) {
printf("x = %5.5f, y = %5.5f\n, z = %5.5f\n", myPoints[i].x, myPoints[i].y, myPoints[i].z);
}

return 0;

}
Topic archived. No new replies allowed.