user3639557 - 1 year ago 84
C++ Question

# numerical precision in recursive functions

I am puzzled, when evaluating the following function it produces number till F(0.8, 172, 1), but when I increase 172 to 173, the result becomes infinite. I suspect there is a numerical precision problem?

``````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);
}
``````

Answer Source

I do not know what your function is supposed to do, but given the arguments: `F(0.8, 172, 1)` the return value is `4.41861e+306` which is just short of the maximum value a `double` can represent:

``````// 1.79769e+308
std::cout << std::numeric_limits<double>::max() << std::endl;
``````

When `172` is replaced with `173`, the return value exceeds the maximum value a `double` can represent and becomes positive infinity. This is made clear by changing the return type of `F` to be `long double` which results in the value `7.56466e+308`

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download