Integrand produced a NaN. Domain error using QuadGK

Hello, everyone. I’m trying to solve numerically the following integral:

\int _{-\infty} ^{\infty} \exp(-z^2/2)\ln(2\cosh(z)) dz = 2.67636.

For that, I write the following

using QuadGK

f3(z) = exp(-z^2/2)*log(2*cosh(z))
V = quadgk(f3,-Inf,Inf)

but I receive the following error message

DomainError with -0.9375:
integrand produced NaN in the interval (-1.0, -0.875)

I’m not being able to understand why I receive this, since the integral converge. Can anyone help?

Your integrand evaluates to 0.0 * Inf for large z, due to underflow+overflow, which gives NaN.

1 Like

You can avoid the NaN problem if you refactor log(2*cosh(z)) in a way that avoids spurious overflow via the identity (for real z): \ln(2\cosh(z)) = |z| + \ln(1 + e^{-2|z|}):

log2cosh(z) = let za = abs(z); za + log1p(exp(-2za)); end

Then you get:

julia> quadgk(z -> exp(-z^2/2) * log2cosh(z), -Inf, Inf)
(2.676363074319933, 1.5888091489219617e-8)
1 Like

Thank you very much!!!