每次迭代时间复杂度O(m*n)
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const double eps=1e-10;
double * solve(double x[][10],double y[],int m,int n)//输入数组x,y训练集大小m,特征数量n
{
static double theta[10];
double alpha=0.01;
double tmp[10];
for(int i=1;i<=m;i++)
x[i][0]=1.0;
for(int i=0;i<=n;i++)
{
theta[i]=0.0;
}
/*for(int i=1;i<=m;i++)
{
for(int j=0;j<=n;j++)
cout<<x[i][j]<<" ";
cout<<endl;
}*/
//int t=100;
while(1)
{
double ans[10];
for(int i=1;i<=m;i++)
{
ans[i]=0.0;
for(int j=0;j<=n;j++)
{
ans[i]=1.0*ans[i]+x[i][j]*theta[j];
}
}
for(int i=0;i<=n;i++)
{
tmp[i]=0.0;
for(int j=1;j<=m;j++)
{
tmp[i]=1.0*tmp[i]+1.0*x[j][i]*(ans[j]-y[j]);
if(i==0)
cout<<" "<<ans[j]<<" "<<y[j]<<endl;
}
}
int tm;
for(tm=0;tm<=n;tm++)
{
if(abs(tmp[tm])>eps)
break;
}
if(tm>n)
{
break;
}
for(int i=0;i<=n;i++)
cout<<theta[i]<<" ";
cout<<endl;
for(int i=0;i<=n;i++)
cout<<tmp[i]<<" ";
cout<<endl<<endl;
for(tm=0;tm<=n;tm++)
{
theta[tm]=1.0*theta[tm]-1.0*alpha*tmp[tm]/(1.0*m);
}
}
return theta;
}
int main()
{
double x[15][10],y[15];
int m=5,n=5;
x[1][1]=1;x[1][2]=1;x[1][3]=2;x[1][4]=-1;x[1][5]=-3;
x[2][1]=2;x[2][2]=1;x[2][3]=2;x[2][4]=-1;x[2][5]=-3;
x[3][1]=3;x[3][2]=4;x[3][3]=1;x[3][4]=-4;x[3][5]=-2;
x[4][1]=1;x[4][2]=0;x[4][3]=1;x[4][4]=-1;x[4][5]=-3;
x[5][1]=1;x[5][2]=1;x[5][3]=2;x[5][4]=-2;x[5][5]=-3;
y[1]=2;
y[2]=3;
y[3]=4;
y[4]=0;
y[5]=1;
double * theta;
theta=solve(x,y,m,n);
for(int i=0;i<=n;i++)
cout<<theta[i]<<endl;
return 0;
}