最小二乘解方程组C语言编程
#include
#include"math.h"
using namespace std;
int main()
{
double **a,*x,*y;
int i,j,m,r,u,k,n,*b;
double max=0,mid,lx;
cout<
cin>>u;
cout<
cin>>m;m=m+1;
x=new double[u];y=new double[u];
cout<
for(i=0;i
cin>>x[i]>>y[i];
for(i=0;i
cout<
a=new double*[m];n=m+1;
for(i=0;i
a[i]=new double[n];
//正规方程组赋值
for(j=0;j
{for(i=0;i
{ for(k=0;k
a[i][j]=max;max=0;
}
}
max=0;
for(i=0;i
{ for(k=0;k
a[i][m]=max;max=0;
}
delete x;
delete y;
for(i=0;i
{
for(j=0;j
{
cout<
}
cout<
}
//消主元
b=new int[m];/*记录列的交换次序*/
for(r=0;r
{ u=r;k=r;max=a[r][r];
//找最大值
for(i=r;i
for(j=r;j
if(fabs(a[i][j])>fabs(max))
{max=a[i][j];u=i;k=j;}
if(max==0)
{cout<
break;
}
cout<
b[r]=r;
//行交换
if(r!=u)
for(j=0;j
{mid=a[u][j];a[u][j]=a[r][j];a[r][j]=mid;}
//列交换
if(r!=k)
{for(i=0;i
{mid=a[i][k];a[i][k]=a[i][r];a[i][r]=mid;}
b[r]=k;
}
cout<
//消元
for(i=r+1;i
{lx=a[i][r]/a[r][r];
for(j=r;j
a[i][j]=a[i][j]-lx*a[r][j];
}
}
//输出消元后增广矩阵
for(i=0;i
{
for(j=0;j
{
cout<