I have a cross-entropy like function, that I want to evaluate. However, I encounter numerical instabilities due to overflows.
I want to compute the cross-entropy of the following function:
$$\sigma(p,q) = \frac{2}{1+e^{d}} \text{ with } d=||p-q||_2^2$$
To be specific, for $z$ in $\{0,1\}$:
$$-z\log(\sigma(p,q))-(1-z)\log(1-\sigma(p,q))$$
I know that there are efficient ways to this for the standard sigmoid
$$\sigma(x) = \frac{1}{(1+e^{-x})}$$
which is also described here:
Doing it in a similar manner, I derived the following equivalent formula:
$$z\log(\frac{1}{2}) + \log(1+e^d) + (z-1)\log(e^d-1))$$
How do I go on from here?
There are problems for $d\approx0$ as well as $d>>0$.
For $x \approx 0$ use the functions $\mathrm{log1p}(x) = \log(1+x)$ and $\mathrm{expm1}(x) = e^x-1$ if available. The other expressions can be computed with $$\log(1+e^d) = \mathrm{log1p}(e^d)$$ and $$\log(e^d-1) = \log(\mathrm{expm1}(d))$$
If the functions are not available use the first terms of the Maclaurin series. For C look e.g. here and here. I guess, today most programming languages have them because they are a recommend operations of the IEEE 754 Floating point standard.
For large $d$ you can simplify $e^d\pm 1 \approx e^d$ and get $\log(1+e^d) \approx \log e^d = d.$
For the complete equivalent formula and large $d$ I just computed the asymptotic expansion with Maple as
$$z d - z \log(2)+(2-z)e^{-d}-\tfrac{1}{2}ze^{-2d} + O(e^{-3d})$$ But I do not know if there is significant cancellation.