实验要求:
给定函数f(x)在 m 个采样点
处的值f(
)以及每个点的权重
(1<= i <= m),求曲线拟合的正交多项式
,满足最小二乘误差
。
函数接口定义:
int OPA( double (*f)(double t), int m, double x[], double w[], double c[], double *eps )
在接口定义中:f是给定函数f(x),m为采样点个数,x传入m个采样点
,w传入每个点的权重;c传回求得的曲线拟合的正交多项式
的系数,eps传入最小二乘误差上限TOL,并且传回拟合的实际最小二乘误差
。
另外,在裁判程序中还定义了常数MAXN,当拟合多项式的阶数达到MAXN却仍未达到精度要求时,即返回 n = MAXN时的结果。
伪代码:
Algorithm: Orthogonal Polynomials Approximation
To approximate a given function by a polynomial with error bounded
by a given tolerance.
Input: number of data m; x[m]; y[m]; weight w[m]; tolerance TOL;
maximum degree of polynomial Max_n.
Output: coefficients of the approximating polynomial.
- 1 Set j0(x) º 1; a0 = (j0, y)/(j0, j0); P(x) = a0 j0(x); err = (y, y) – a0 (j0, y);
- 2 Set a1= (xj0, j0)/(j0, j0); j1(x) = (x – a1) j0(x);
- 1 = (j1, y)/(j1, j1); P(x) += a1 j1(x); err -= a1 (j1, y);
Step 3 Set k = 1;
- 4 While (( k < Max_n)&&(|err|³TOL)) do steps 5-7
Step 5 k ++;
- 6 ak= (xj1, j1)/(j1, j1); bk-1 = (j1, j1)/(j0, j0);
- 2(x) = (x – ak) j1(x) – bk-1 j0(x); ak = (j2, y)/(j2, j2);
- (x) += ak j2(x); err -= ak (j2, y);
- 7 Set j0(x) = j1(x); j1(x) = j2(x);
Step 8 Output ( ); STOP.
c语言实现: #include
#include
#define MAXM 200 /* 采样点个数上限*/ #define MAXN 5 /* 拟合多项式阶数上限*/ /* 这里仅给出2个测试用例,正式裁判程序可能包含更多测试用例 */ double qi_x[MAXN+1][MAXN+1];//存储基底函数 double ak[MAXN+1];//存储拟合函数对应基地的系数 double f1(double x) { return sin(x); } double f2(double x) { return exp(x); } //用于求x的n次方 double power(double x,int n) { int i; double y=1; for(i=0;i
0;i--) temp[i]=x[i-1]; temp[0]=0; } //用于完成拟合函数和基底函数的内积 double get_function_inner_product(double (*f)(double t),double x[],double y1[],double w[],int m) { int i,j; double sum=0; double sum1; for(i=0;i
=*eps)) { k=k+1; double temp1[MAXN+1]={0}; carry_x(qi_x[k-1],temp1); m1=get_Inner_product(x,temp1,qi_x[k-1],w,m)/get_Inner_product(x,qi_x[k-1],qi_x[k-1],w,m); n=get_Inner_product(x,qi_x[k-1],qi_x[k-1],w,m)/get_Inner_product(x,qi_x[k-2],qi_x[k-2],w,m); Array_op(k,m1,n); // printf("%f\n",get_function_inner_product(f,x,qi_x[k],w,m)); ak[k]=get_function_inner_product(f,x,qi_x[k],w,m)/get_Inner_product(x,qi_x[k],qi_x[k],w,m); // printf("%f\n",ak[k]); err=err-ak[k]*get_function_inner_product(f,x,qi_x[k],w,m); } *eps=err; return k; } //输出实验结果 void print_results( int n, double c[], double eps) { /* 用于输出结果 */ int i; int m,k; for(m=0;m
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/215056.html原文链接:https://javaforall.net
