<p>Richard Critten's comment says:</p>

<blockquote>
  <p>"...Some implementations may occasionally return infinity if RealType is float. This is LWG issue 2524..." source (has a link to the issue): <a href="https://en.cppreference.com/w/cpp/numeric/random/exponential_distribution" rel="nofollow noreferrer">https://en.cppreference.com/w/cpp/numeric/random/exponential_distribution</a></p>
</blockquote>

<p>Switching to <code>double</code> doesn't fix this problem, but rather, it merely reduces the chance of seeing it (or at least makes it negligible). As the LWG issue points out, the underlying issue is that <code>generate_canonical</code> (which some implementations could make use of) might return 1.0 in rare cases, so that <code>-log(1-generate_canonical())</code> could output infinity. In practice, this was more likely with <code>float</code> than with <code>double</code> since there are considerably fewer numbers that <code>generate_canonical</code> could produce with <code>float</code> than with <code>double</code> (in practice, 2^24 as opposed to 2^53). (In any case, there are other problems with naive implementations of right-tailed distributions, such as the exponential distribution; see "<a href="https://arxiv.org/abs/1704.07949" rel="nofollow noreferrer">Reconditioning your quantile function</a>".)</p>
C++ exponential_distribution occasionally returns inf where 0 is expected
<p>In a project, I am generating millions of expo(lambda) random variables, where lambda is potentially very large. When using <code>std::exponential_distribution&lt;float&gt;</code> I occasionally get a return value of <code>inf</code>. I would understand this if lambda were close to 0, but when lambda is large a value very close to zero is expected. For example, the following program usually terminates after several million draws:</p>

<pre><code>#include&lt;iostream&gt;
#include&lt;random&gt;

int main(void)
{
    std::random_device rd;
    std::mt19937 generator(rd());

    float lambda = 1000000.0;
    float val = 0;

    for(int i = 0; i &lt; 1000000000; ++i)
    {
        std::exponential_distribution&lt;float&gt; dist(lambda);
        val = dist(generator);

        if(isinf(val))
        {
            std::cout &lt;&lt; i &lt;&lt; " " &lt;&lt; val &lt;&lt; " failure" &lt;&lt; std::endl;
            exit(0);
        }
    }

    return 0;
}
</code></pre>

<p>If there is some error (due to precision) in the function, why does it return <code>inf</code> instead of the more convenient <code>0.0</code>? Is there any way to fix this, besides for manually checking that the output is finite? Thanks. </p>