C++实现最小二乘法对y=exp(x)的二次拟合

#include<iostream>
#include<math.h>
const int N=20;
const int n=3;
double A[n][n];
	double B[n];
	double start=0, end=1.0;//积分范围
const double PI=3.1415926;
using namespace std;
void HibertMatrix();
double func1(double x);
double func2(double x);
void projectAarry();
void jacobi();
int main()
{
	double A[n][n];
	double B[n];
	double start=0, end=1.0;//积分范围
	HibertMatrix(); //生成希尔伯特矩阵
	projectAarry();//生成投影矩阵
    jacobi();//求解正规方程
return 0;
}
void HibertMatrix()//希尔伯特矩阵的生成
{
	for(int i=0;i<n;i++)
	for(int j=0;j<n;j++)
	A[i][j]=1.0/(i+j+1);
}
double func1(double x)    //Expansion function
{  
    return exp(x);  
}  
double func2(double x)  //Base function
{
	return x;
	
}
void projectAarry()
{
	double h=(end-start)/N;
	for(int i=0;i<n;i++)
	{
	 B[i]=(pow(func2(start),i)*func1(start)+pow(func2(end),i)*func1(end))*h/2;
	for(int k=1;k<N;k++) 
	B[i]+=pow(func2(start+k*h),i)*func1(start+k*h)*h;
	cout<<B[i]<<'\t';
}
cout<<endl;
}
void jacobi()
{
	
//	  double A[N][N]={{10,-1.0,-2.0},{-1.0,10.0,-2.0},{-1.0,-1.0,5.0}};  
 //   double B[N]={72,83,42};  
    double X[N]={0,0,0,};  
for (int k=0;k<100;k++)  
{  
for(int i=0;i<n;i++)  
{  
double sum=0;  
for(int j=0;j<n;j++)  
{  
    if(j==i) continue;  
    sum+=A[i][j]*X[j];  
}  
X[i]=(B[i]-sum)/A[i][i];  
}  
}  
for (int i=0;i<n;i++)  
    cout<<X[i]<<'\t';  
    cout<<endl;  
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值