我很困惑,在评估以下函数时它会产生直到 F(0.8, 172, 1) 的数字,但是当我将 172 增加到 173 时,结果变成无限大。我怀疑存在数值精度问题?
double F(double d, int c, int t) {
// base cases
if ((c==1 && t==1) || (c==0 && t==0))
return 1.;
if (c==0 || t==0)
return 0.;
if (t>c)
return 0.;
return F(d,c-1,t-1) + (c-1 - t*d)*F(d,c-1,t);
}
最佳答案
我不知道你的函数应该做什么,但给定参数:F(0.8, 172, 1)
返回值是 4.41861e+306
这刚好小于 double
可以表示的最大值:
// 1.79769e+308
std::cout << std::numeric_limits<double>::max() << std::endl;
当172
被替换为173
时,返回值超过了double
所能表示的最大值,变为正无穷大。通过将 F
的返回类型更改为 long double
这导致值 7.56466e+308
关于c++ - 递归函数中的数值精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40647449/