我正在尝试根据以下算法创建 gauss-legendre 代码:
对于 n 个点
也就是说,它创建了一个 2n 方程系统(如果我们要求对 2n-1 阶的多项式准确,
ti是n阶legendre多项式的根。legendre多项式给出:
和 wi :
我的代码是:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <iomanip>
#include <cmath>
using namespace std;
const double pi=3.14;
//my function with limits (-1,1)
double f(double x){
double y;
y=(pi/4.0)*(log((pi*(x+1.0))/4.0 +1.0));
return y;
}
double legendre (int n){
double *L,*w,*t;
double x,sum1,sum2,result;
L=new double [n];
w=new double [n];
t=new double [n];
while(n<10){
L[0]=1;
L[1]=x;
//legendre coef
for (int i=1;i<=10;i++){
L[i+1]=((2.0*i+1.0)*x*L[i] - i*L[i-1])/(i+1.0);
}
//weights w
w=0;
for (int i=1;i<=10;i++){
w[i]+=(2.0*(1.0-x*x))/(i*i*(L[i-1]*L[i-1]));
}
//sums w*t
for (int i=1;i<=10;i++){
sum1=0.0; //for k=1,3,5,2n-1
for (int k=1;k<=2*n-1;k+=2){
sum1+=w[i]*(pow(t[i],k));
}
sum1=0;
sum2=0.0;//for k=0,2,4,2n-2
for(int k=0;k<=2*n-2;k+=2){
sum2+=w[i]*(pow(t[i],k));
}
sum2=2.0/n;
}
}
result=w*f(*t);
return result;
}
int main()
{
double eps=1e-8;//accuracy
double exact=0.8565899396;//exact solution for the integral
double error=1.0;
double result;
int n=1;//initial point
while (fabs(result-exact)>eps) {
result=legendre(n);
cout <<"\nFor n = "<<n<<",error = "<<fabs(error-exact)<<",value = "<<result;
n++;
}
return 0;
}
我的问题是:
1) 编译器给了我 :error: 'double*' 和 'double' 类型的无效操作数到二进制 'operator*' --> 在 result=w*f(*t);
2)我不确定我是否做对了整个事情。我的意思是,如果我将所有事情组合在一起并且我是否正确实施了算法。