最小二乘法拟合直线
 /*-------------------------------------------------*/
/* 这个程序实现计算高度和臭氧含量的线性模型,
使用最小二乘法,对于拟合直线 y=mx+b 有:
m=[sum(x)*sum(y)-n*sum(x*y)]/[(sum(x))^2-n*sum(x^2)]
b=[sum(x)*sum(x*y)-sum(x^2)*sum(y)]/[(sum(x))^2-n*sum(x^2)]
其中x,y分别为(x1,y1),(x2,y2),...(xn,yn).
copy from Engineering Problem Solving with C++.
by Edison Wang date: 2009-7-22
*/
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
int count(0);
double x(0),y(0),first,last,sumx(0),sumy(0),
sumx2(0),sumxy(0),denominator,m,b;
string filename;
ifstream zonel;
cout << "Enter the data file name: ";
cin >>filename;
//open file
zonel.open(filename.c_str());
if (zonel.fail()) {
cout << "Error opening file\n";
}
else{
//while not at the end of the files
//read and accumulate information.
zonel >>x >>y;
while (!zonel.eof()) {
++count;
if (count==1) {
first = x; //保存第一个数据
}
sumx += x;
sumy += y;
sumx2 += x*x;
sumxy += x*y;
zonel >>x >>y;
}
last = x; //保存最后一个数据
//compute slope(斜率) and y-intercept(y截距).
denominator = sumx*sumx - count*sumx2; //计算分母
m = (sumx*sumy - count*sumxy)/denominator;
b = (sumx*sumxy-sumx2*sumy)/denominator;
//set format flags
cout.setf(ios::fixed);
cout.precision(2);
//Print summary information
cout <<"\nRange of altitudes in km: \n";
cout <<first <<"to" << last <<endl <<endl;
cout <<"Linear model: \n";
cout <<"ozone-mix-ratio="<<m<<" altitude + "<<b <<endl;
//close file
zonel.close();
} //end of else
return 0;
}
    /* 这个程序实现计算高度和臭氧含量的线性模型,
使用最小二乘法,对于拟合直线 y=mx+b 有:
m=[sum(x)*sum(y)-n*sum(x*y)]/[(sum(x))^2-n*sum(x^2)]
b=[sum(x)*sum(x*y)-sum(x^2)*sum(y)]/[(sum(x))^2-n*sum(x^2)]
其中x,y分别为(x1,y1),(x2,y2),...(xn,yn).
copy from Engineering Problem Solving with C++.
by Edison Wang date: 2009-7-22
*/
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
int count(0);
double x(0),y(0),first,last,sumx(0),sumy(0),
sumx2(0),sumxy(0),denominator,m,b;
string filename;
ifstream zonel;
cout << "Enter the data file name: ";
cin >>filename;
//open file
zonel.open(filename.c_str());
if (zonel.fail()) {
cout << "Error opening file\n";
}
else{
//while not at the end of the files
//read and accumulate information.
zonel >>x >>y;
while (!zonel.eof()) {
++count;
if (count==1) {
first = x; //保存第一个数据
}
sumx += x;
sumy += y;
sumx2 += x*x;
sumxy += x*y;
zonel >>x >>y;
}
last = x; //保存最后一个数据
//compute slope(斜率) and y-intercept(y截距).
denominator = sumx*sumx - count*sumx2; //计算分母
m = (sumx*sumy - count*sumxy)/denominator;
b = (sumx*sumxy-sumx2*sumy)/denominator;
//set format flags
cout.setf(ios::fixed);
cout.precision(2);
//Print summary information
cout <<"\nRange of altitudes in km: \n";
cout <<first <<"to" << last <<endl <<endl;
cout <<"Linear model: \n";
cout <<"ozone-mix-ratio="<<m<<" altitude + "<<b <<endl;
//close file
zonel.close();
} //end of else
return 0;
}

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号