从 PASCAL 到 C++ 的代码转换给出了意想不到的结果
Code translation from PASCAL to C++ giving unexpected results
我正在尝试实现本文中给出的PASCAL代码C++,我的尝试是
#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,而根据等式 12 和论文中给出的表格,我预计 31/35 = 0.88571。我的错误在哪里?
您的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
第一个函数GenFact
应该返回一个float
或double
而不是int
。因此gf
也应该是浮点类型。
其次,你的函数Weight
与论文中的函数不同。我想你错过了GenFact(2 * m, k)
部分
除了前面的答案 - 你应该除以 GenFact(2.0 * m + k + 1.0, k + 1.0)
,而不是乘以(至少论文是这样说的)。
相关文章:
- 为什么在递归中使用循环会产生意想不到的结果?
- 字符到int8_t转换会产生意想不到的结果?
- libc++ 对 std::map/set::equal_range 的实现给出了意想不到的结果
- 微小加密算法实现会产生意想不到的结果
- 使用 std::set 的 .begin() 和 .end() 函数会产生意想不到的结果
- 在我的C++链表实现中取消引用节点指针,给出意想不到的结果
- C++正则表达式Visual Studio Community 2015给出<regex>意想不到的结果
- istringstream int8_t产生意想不到的结果
- 划分 OpenCV 垫会产生意想不到的结果
- 提升精神,提升任何意想不到的结果
- regex_match给出意想不到的结果
- 从 PASCAL 到 C++ 的代码转换给出了意想不到的结果
- 意想不到的结果c++
- 在lambda上使用条件运算符调用std::any_of会得到意想不到的结果
- vector::insert在VS2010中执行意想不到的结果
- list resize会产生意想不到的结果
- CUDA: 2D数组索引产生意想不到的结果
- 将字符串转换为整数会产生意想不到的结果
- 在c++中,一些宏语句可能会产生意想不到的结果
- Visual Studio可变宏展开会产生意想不到的结果