# Avoid cancellation errors for approximating the derivative of the sine function

The function $f_1(x_0,h) = \sin(x_0+h) - \sin(x_0)$ can be transformed into another form, $f_2(x_0,h)$, using the trigonometric formula:

$$\sin(\phi)-\sin(\psi) = 2\cos\left(\dfrac{\phi +\psi}{2}\right)\sin\left(\dfrac{\phi -\psi}{2}\right)$$

Thus,$f_1$ and $f_2$ have the same values, in exact arithmetic, for any given argument values $x_0$ and $h$.

a) Derive $f_2(x_0,h)$.

Using the trigonometric formula above, I get:

\begin{gather*}\phi = x_0+h,\quad\psi=x_0,\\\\ f_2(x_0,h)=2\cos\left(\dfrac{x_0+h+x_0}{2}\right)\sin\left(\dfrac{x_0+h-x_0}{2}\right) = 2\cos\left(x_0+\dfrac{h}{2}\right)\sin\left(\dfrac{h}{2}\right) \end{gather*}

b) Suggest a formula that avoids cancellation errors for computing the approximation $\dfrac{f(x_0+h)-f(x_0)}{h}$ to the derivatives of $f(x) = \sin(x)$ at $x=x_0$.

Here is my work: $$f'(x)=\dfrac{f(x_0+h)-f(x_0)}{h} =\dfrac{\sin(x_0+h)-\sin(x_0)}{h}$$

Then I plugged in the formula from (a):

$$f'(x) =\dfrac{2\cos\left(x_0+\dfrac{h}{2}\right)\sin\left(\dfrac{h}{2}\right)}{h}$$

Then I tried to use the trig identity $\cos(s+t) = \cos(s)\cos(t)-\sin(s)\sin(t)$ So the formula becomes

$$f'(x) =\dfrac{2\left[\cos(x_0)\cos\left(\dfrac{h}{2}\right)-\sin(x_0)\sin\left(\dfrac{h}{2}\right)\right]\sin\left(\dfrac{h}{2}\right)}{h}$$

And I am now stuck. How can I change the formula so that the cancellation errors would be avoided? Thanks in advance for any hints.

-
After you wrote "Then I plugged in the formula from (a) " in the numerator there is a term sinx missing. Moreover, shouldn't the x0 in the cos term be divided by 2 as well? – imranfat Sep 21 '13 at 22:07
I don't understand the whole point of this exercise. The derivative of the sine function is (very) well known, and that derivative can be calculated by various means (e.g., the Taylor series, which converges rather quickly). – dfeuer Sep 21 '13 at 22:25
@imranfat, I have made some changes and I hope the question is clear now. – user59036 Sep 21 '13 at 22:28
great, now distribute the last sin term, split the fraction. I can see a standard limit of the form (sinx)/x after some deliberation with that h/2. Taking the limit gives cosx times 1, so cosx. The second fraction also has that standard limit AND an extra sinh term. with h going to zero, this term cancels. In essence, you are almost there. – imranfat Sep 21 '13 at 22:32

You already did the important work in your equation under "Then I plugged in..." There is no subtraction here any more, which is the point. In the original, say $x\frac \pi4$ so $\sin x=\frac {\sqrt 2} 2$ If $h$ is small, say $10^{-6}$, you will lose five decimal digits of precision by subtracting the two sines. Quit while you are ahead.