利用勒让德多项式进行拟合的区域是[-1,1],如果不是这个区域,比如是[a,b],利用转化到[-1,1]。
参考以下例题计算系数
C语言代码如下
//用三阶的勒让德多项式进行拟合
#include<math.h>
#include<stdio.h>
#include "main.c"
double f(double x);
double fl1(double x);
double fl2(double x);
double fl3(double x);
int main(){
double a=-1.0,b=1.0;
int n=600;
double c0=integrate(f,a,b,n)*0.5;
double c1=integrate(fl1,a,b,n)*1.5;
double c2=integrate(fl2,a,b,n)*2.5;
double c3=integrate(fl3,a,b,n)*3.5;
double x=1;
printf("%lf %lf %lf %lf",c0,c1,c2,c3);
}
//要拟合的函数
double f(double x){
return exp(x);
}
//拟合之后的结果
double f1(double x,double c0,double c1,double c2,double c3){
return c0-0.5*c2+x*(c1-1.5*c3)+x*x*1.5*c2+pow(x,3)*2.5*c3;
}
//1到3阶要积分的函数
double fl1(double x){
return x*f(x);
}
double fl2(double x){
return (1.5*x*x-0.5)*f(x);
}
double fl3(double x){
return (2.5*pow(x,3)-1.5*x)*f(x);
}
integrate为求积分的函数,见下
//梯形公式计算数值积分,a下限,b上限,n分的区间个数
double integrate(double (*f)(double), double a, double b, int n) {
double h = (b - a) / n; // 区间宽度
double sum = 0.5 * (f(a) + f(b)); // 初始值
int i;
for (i = 1; i < n; i++) {
sum += f(a + i * h);
}
return h * sum;
}
如果用MATLAB,则可以使用函数句柄
fun=@(x) exp(x);
f1=@(x) x.*fun(x);
f2=@(x) (1.5.*x.*x-0.5).*fun(x);
f3=@(x) (2.5.*x.^3-1.5.*x).*fun(x);
a=-1;
b=1;
c0=0.5*integral(fun,a,b);
c1=1.5*integral(f1,a,b);
c2=2.5*integral(f2,a,b);
c3=3.5*integral(f3,a,b);
fun1=@(x) c0-0.5*c2+(c1-1.5*c3)*x+1.5*c2*x.^2+2.5*c3*x.^3;
fun1(1)