Least Square Method for fitting a straight line c ++ Program

Source: Internet
Author: User

// Point. h
Class Point // Point class declaration
{
Public: // external interface
Point (float xx = 0, float YY = 0) {x = xx; y = YY ;}
Float getx () {return X ;}
Float Gety () {return y ;}
Friend float linefit (point l_point [], int n_point); // youyuan Function
// Int type variable is the number of points
PRIVATE: // Private Data Member
Float X, Y;
};
// End of point. h

// Main. cpp
# Include <iostream>
# Include <cmath>
# Include "point. H"
Using namespace STD;
Float linefit (point l_point [], int n_point) // youyuan function body
{
Float av_x, av_y; // declare the variable
Float l_xx, l_yy, l_xy;
// Variable Initialization
Av_x = 0; // The average value of X
Av_y = 0; // The average value of Y
L_xx = 0; // LXX
Rochelle YY = 0; // lyy
Rochelle xy = 0; // lxy
For (INT I = 0; I <n_point; I ++) // calculate the average values of X and Y
{
Av_x + = l_point [I]. X/n_point;
Av_y + = l_point [I]. Y/n_point;
}
For (I = 0; I <n_point; I ++) // calculate LXX, lyy, and lxy
{
Rochelle xx + = (Rochelle point [I]. X-av_x) * (Rochelle point [I]. X-av_x );
Rochelle YY + = (Rochelle point [I]. Y-av_y) * (Rochelle point [I]. Y-av_y );
Roxy + = (Rochelle point [I]. X-av_x) * (Rochelle point [I]. Y-av_y );
}
Cout <"this line can be fitted by Y = ax + B." <Endl;
Cout <"A =" <l_xy/l_xx; // output regression coefficient
Cout <"B =" <av_y-L_xy * av_x/l_xx <Endl; // output regression coefficient B
Return float (l_xy/SQRT (l_xx * l_yy); // return the correlation coefficient R
}

Int main ()
{
Point l_p [10] = {point (6, 10), point (14,20), point (26, 30 ),
Point ),
Point (100,100), Point (), Point ()}; // initialize the data Point
Float r = linefit (l_p, 10); // linear regression calculation
Cout <"Line coefficient r =" <r <endl; // output Correlation coefficient
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.