Robustly dealing with multiple roots in integrals of rational functions I have an application where I numerically need to calculate integrals of rational functions. Some of the actual integrals are a bit different, but as an example we can consider an integral of the form $$\int_{0}^\infty \frac{1}{(x-r)(x-s)(x-t)} dx$$
where $r,s,t < 0$. We have three different cases, depending on whether any of the roots $r,s,t$ are equal, and if so, how many of them are equal.

*

*All distinct. In this case, we get $$\int_{0}^\infty \frac{1}{(x-r)(x-s)(x-t)} dx = \frac{-(s-t)\ln(-r)+(r-t)\ln(-s)-(r-s)\ln(-t)}{(r-s)(r-t)(s-t)}$$


*Two roots equal, say $r = t$. In this case, we get $$\int_{0}^\infty \frac{1}{(x-r)(x-s)(x-t)} dx = \int_{0}^\infty \frac{1}{(x-r)^2(x-s)}dx = \frac{r\ln(r/s)-(r-s)}{r(r-s)^2}$$


*All roots equal. In this case, we get $$\int_{0}^\infty \frac{1}{(x-r)(x-s)(x-t)} dx = \int_{0}^\infty \frac{1}{(x-r)^3}dx = \frac{1}{2r^2}$$
Mathematically, these cases are of course distinct and well-defined. Numerically, however, the cases are not quite distinct. For example, if $s$ is very different from either $r$ or $t$, but $r$ and $t$ are very close but still distinct, then the expression from 2) can be more appropriate to use than the expression from 1), in order to avoid cancellation problems. It is of course easy to see that taking the limit $t \to r$ in expression 1) gives expression 2).
What is the best way to deal with these issues? Is it possible to write down a single expression that will numerically work well regardless of possible degeneracy between the roots?
 A: Consider $t\to r$ and Taylor expand the numerator of your first case to see that
\begin{align}&\color{#aa4422}{(t-s)\ln(-r)}+(r-t)\ln(-s)+\color{#2277ff}{(s-r)\ln(-t)}\\&=\color{#aa4422}{(r-s)\ln(-r)+(t-r)\ln(-r)}\\&\quad+(r-t)\ln(-s)\\&\quad+\color{#2277ff}{(s-r)\ln(-r)+\frac{s-r}r(t-r)-\frac{s-r}{r^2}(t-r)^2+\mathcal O(t-r)^3}\\&=\color{#aa4422}{(t-r)\ln(-r)}+(r-t)\ln(-s)+\color{#2277ff}{\frac{s-r}r(t-r)-\frac{s-r}{r^2}(t-r)^2+\mathcal O(t-r)^3}\\&=(t-r)\left[\ln(r/s)+\frac{s-r}r-\frac{s-r}{r^2}(t-r)\right]+\mathcal O(t-r)^3\end{align}
Cancelling with the denominator, you will find this gives $\mathcal O(t-r)^2$ error, so this formula should be used if $(t-r)^2$ is very small (say $10^{-16}$).
The key thing to note here is that by Taylor expanding we were able to cancel off the $(r-s)\ln(-r)$ terms. This allows us to avoid catastrophic cancellation.
The same approach may be used if multiple variables end up causing cancellations similar to this, though you will have to use a multivariable Taylor expansion.
