how to improve numerical stability

293 Views Asked by At

I'm trying to improve the numerical stability of $(x+1)(x-1)(x-2)/(x^2+4)$. I already have turned it into $(x+1)(x-1)/(x+2)$ and NaN if $x=2$. I realize that I can't make it better around $x=-2$ due to bad condition, but I'm still trying to improve it around $x=1$ and $x=-1$, i.e. I don't want to take the difference between two numbers that are almost equal.

1

There are 1 best solutions below

0
On

You can't unless you know something about $x$ that lets you add or subtract $1$ analytically. If I just tell you $x=0.99999953243$ you will lose six digits when you subtract it from $1$. If I tell you that $x$ came from a calculation you might be able to look at the calculation and do better. For example, if $x=\sqrt{1-\frac 1{1,000,000}}$ you can compute the Taylor series of the square root around $1$, subtract the $1$ analytically, and have good accuracy for the result.