我正在尝试在C ++中实现this paper中给出的PASCAL代码,我的尝试是
#include <iostream>
using namespace std;
int GenFact(int a, int b)
{ // calculates the generalised factorial
// (a)(a-1)...(a-b+1)
int gf = 1;
for (int jj = (a - b + 1); jj < a + 1; jj++)
{
gf = gf * jj;
}
return (gf);
} // end of GenFact function
double GramPoly(int i, int m, int k, int s)
{ // Calculates the Gram Polynomial ( s = 0 ),
// or its s'th
// derivative evaluated at i, order k, over 2m + 1 points
double gp_val;
if (k > 0)
{
gp_val = (4.0 * k - 2.0) / (k * (2.0 * m - k + 1.0)) *
(i * GramPoly(i, m, k - 1, s) +
s * GramPoly(i, m, k - 1.0, s - 1.0)) -
((k - 1.0) * (2.0 * m + k)) /
(k * (2.0 * m - k + 1.0)) *
GramPoly(i, m, k - 2.0, s);
}
else
{
if ((k == 0) && (s == 0))
{
gp_val = 1.0;
}
else
{
gp_val = 0.0;
} // end of if k = 0 & s = 0
} // end of if k > 0
return (gp_val);
} // end of GramPoly function
double Weight(int i, int t, int m, int n, int s)
{ // calculates the weight of the i'th data
// point for the t'th Least-square
// point of the s'th derivative, over 2m + 1 points, order n
double sum = 0.0;
for (int k = 0; k < n + 1; k++)
{
sum += (2.0 * k + 1.0) *
GenFact(2.0 * m + k + 1.0, k + 1.0) *
GramPoly(i, m, k, 0) * GramPoly(t, m, k, s);
} // end of for loop
return (sum);
} // end of Weight function
int main()
{
double z;
z = Weight(-2, -2, 2, 2, 0);
cout << "The result is " << z;
return 0;
}
然而,当我运行代码时,输出是1145,而我期望31/35 = 0.88571,如公式12和论文中给出的表格。我的错误在哪里?
答案 0 :(得分:1)
第一个函数GenFact
应该返回float
或double
而不是int
。因此gf
也应该是一个浮点类型。
其次,您的函数Weight
与论文中的函数不同。我想你错过了GenFact(2 * m, k)
答案 1 :(得分:1)
除了上一个答案之外 - 你应该除以GenFact(2.0 * m + k + 1.0, k + 1.0)
,而不是乘以(至少论文是这样说的)。
答案 2 :(得分:1)
您的Weight
功能有误 - 有一个术语丢失了......试试这个:
double Weight( int i , int t , int m , int n , int s )
{ // calculates the weight of the i'th data point for the t'th Least-square
// point of the s'th derivative, over 2m + 1 points, order n
double sum = 0.0 ;
for ( int k = 0 ; k <= n ; k++ )
{
sum += (2*k+1) *
(
GenFact(2*m,k) / //<-- here
GenFact(2*m+k+1,k+1)
) * GramPoly(i,m,k,0) * GramPoly(t,m,k,s) ;
} // end of for loop
return ( sum ) ;
} // end of Weight function