Avoid Loss of significance error I want to compute $f(x)$to avoid loss of significance$$f(x)=\frac{1-\cos x}{x^2}$$
One way is writing Taylor series approximation for $\cos x$ about $x=0$. what about this approach:
$$f(x)=\frac{2\sin^2(\frac x2)}{x^2}$$
Is this ok ?

You are already mindful of rounding errors, but that is not the only issue here.

*

*In IEEE floating point arithmetic, $0/0$ evaluates as NaN (not a number). You need a conditional statement to ensure that $f(0)$ is evaluated as $\frac{1}{2}$.

*In IEEE double precision, the largest positive number is $(2-2^{-52})\cdot 2^{1023}$, so $x^2$ will certainly overflow to infinity when $|x| \ge 2^{512}$ and the default rounding mode is active. If you evaluate $f$ as you suggested, i.e., $$f(x) = 2 \frac{\sin^2\left(\frac{x}{2}\right)}{x^2},$$ and $x^2$ overflows, then the computed result of $f(x)$ is zero. You avoid this issue by evaluating $f$ as $$f(x) = 2 \left(\frac{\sin\left(\frac{x}{2}\right)}{x}\right)^2.$$

*Be mindful of approximations that are more accurate than the rounding error associated with their evaluation.

In general, we seek to compute a target value $T$. We most then choose an approximation $A$ as well as an algorithm for evaluating $A$. In general, the computed value $\hat{A}$ of $A$ will be different from $A$. The total error is $$T-\hat{A} = (T - A) + (A - \hat{A}).$$ Ideally, the two contributions, i.e., the approximation error $T-A$ and the rounding error $A - \hat{A}$ should have the same size and the total error should be less than the user's tolerance $\tau$. Suppose $|T-\hat{A}| < \tau$.

*

*If $|T-A| \ll |A-\hat{A}|$, then we are guilty of mathematical overkill and are probably wasting CPU cycles because very accurate approximations tend to be more costly to evaluate than less accurate approximations.

*If $|A-\hat{A}| \ll |T-A|$, then we are guilty of algorithmic overkill and we may be able to find a faster, less accurate algorithm. It may well be enough to execute the same basic algorithm in single precision instead of double precision.

