#include <iostream>
using namespace std
const int MAXNUM = 3
int main()
{
double x[MAXNUM],y[MAXNUM]
double sumx=0,sumy=0,sumxy=0,sumxx=0
double a,b
int i
cout<<"输入"<<MAXNUM<<"组样本:"
for (i=0i<MAXNUMi++)
{
cin>>x[i]>>y[i]
sumx += x[i]
sumy += y[i]
sumxy = x[i]*y[i]
sumxx = x[i]*x[i]
}
double averagex,averagey
averagex = sumx/MAXNUM
averagey = sumy/MAXNUM
b = (sumxy - MAXNUM*averagex*averagey)/(sumxx - MAXNUM*averagex*averagex)
a = averagey - b*averagex
cout<<"线性拟合曲线为:y="<<a<<"+"<<b<<"*y\n"
return 0
}
最小二乘法?给你个代码吧,C++的
#include
<iostream>
#include
<fstream>
#include
<vector>
using
namespace
std
void
BinSolve(vector<double>
va,vector<double>
vb,double
&a0,double
&b0)
int
main(int
argc,char**
argv)
{
double
a=0,b=0
if(argc!=2)
{
cout<<"Usage:bin.exe
FileName.txt\n"
return
0
}
else
{
cout<<"程序不对常规错误进行检验,请自行校验~~\n"
cout<<"Version
1.0,
By
cdinten.^_^\n"
vector<double>
va
ifstream
in(argv[1])
for(double
din>>d
)
{
va.push_back(d)
}
int
cnt=va.size()
vector<double>
vb(va.begin()+cnt/2,va.end())
va.resize(cnt/2)
BinSolve(va,vb,a,b)
}
cout<<"=============================\n"
cout<<"a="<<a<<",b="<<b<<endl
cout<<"=============================\n"
return
0
}
void
BinSolve(vector<double>
va,vector<double>
vb,double
&a0,double
&b0)
{
double
t1=0,t2=0,t3=0,t4=0
for(int
i=0i<va.size()i++)
{
t1+=va[i]*va[i]
t2+=va[i]
t3+=va[i]*vb[i]
t4+=vb[i]
}
a0=(t3*va.size()-t2*t4)/(t1*va.size()-t2*t2)
b0=(t1*t4-t2*t3)/(t1*va.size()-t2*t2)
}
你把数据准备在一个in.txt得文件中,例如内容如下:
0
1
2
3
4
5
6
7
27.0
26.8
26.5
26.3
26.1
25.7
25.3
24.8
拟合直线之后会有一个拟合结果表,在这个表里有直线的方程,斜率值(slop),截距值(intercept),以及这些值的误差(error),和拟合结果的r^2(越接近于1,表明拟合结果越好)。如果没有看到这个表,那么点击菜单栏上的view
-
results
log,就能看到了。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)