I need to compute the mean and variance of the truncated normal distribution. For simplicity, let us focus on a standard normal, since the general case can be reduced to this. The PDF is given by:
$$f\left(x;a,b\right)=\begin{cases} \frac{\phi\left(x\right)}{\Phi\left(b\right)-\Phi\left(a\right)} & a\le x\le b\\ 0 & \text{otherwise} \end{cases}$$
where
$$\phi\left(x\right)=\frac{1}{\sqrt{2\pi}}\mathrm{e}^{-x^{2}/2},\quad\Phi\left(x\right)=\frac{1}{2}\left(1+\mathrm{erf}\left(x/\sqrt{2}\right)\right)$$
The analytical formulas for the mean and variance of $f$ are:
$$\left\langle x\right\rangle =\frac{\phi\left(a\right)-\phi\left(b\right)}{\Phi\left(b\right)-\Phi\left(a\right)}$$
$$\mathrm{var}\,x =1+\frac{a\phi\left(a\right)-\beta\phi\left(b\right)}{\Phi\left(b\right)-\Phi\left(a\right)}-\left(\frac{\phi\left(a\right)-\phi\left(b\right)}{\Phi\left(b\right)-\Phi\left(a\right)}\right)^{2}$$
However, if you try to evaluate those expressions numerically, when $a,b$ are sufficiently away from the mean, you will encounter multiple numerical issues. I have tried Mathematica, Python scipy, Julia Distributions.jl, and they all give NaN.
For example, this is what happens in Mathematica:
Has anyone encountered this issue before? Anyone can suggest a solution, or an alternative package?
Simplify[ Series[Log[CDF[NormalDistribution[], -a]], {a, Infinity, 6}], Assumptions -> a > 0]
. $\endgroup$