MATLAB: Taylor Series for sine function

MATLABnumerical analysis

I'm trying to code the sine function using the taylor series with x_0 dependent on x, and -10 <= x <= 10; however, I'm kind of stuck on how to do it. I'm trying to code using only basic operations and the modulo function. What I'm mainly having trouble with is coding the trig identities within my function. For example,
sin(x + pi/2) = cos(x)
cos(x + pi/2) = -sin(x)
Anyone have any helpful tips for trying to switch the cosine and sine values at a particular x, without using a transcedental function, or how to go about coding sine in general that may help relieve me of my problem with the trig identities?

Best Answer

(Note: you might decide to read how I coded trig functions in my HPF toolbox. But that would be wild overkill for basic homework.)

So, think. What does this do for you?

Xhat = mod(x,2*pi);

Where does Xhat live, as compared to x? What do you know about sin(Xhat), as compared to sin(x)? If you are not sure, try some values! Play around. THINK! For example...

sin(10)
ans =
     -0.54402
sin(mod(10,2*pi) - pi)
ans =
      0.54402

Can you do better? Of course. The Taylor series for the sine function will converge better if Xhat lives in the range [-pi,pi), instead of [0,2*pi).

You can pretty easily deal with that, since you would have this identity:

sin(x - pi) = -sin(x)

That suggests you can do this:

Xhat = mod(x,2*pi) - pi;

Where does Xhat now live?

Can you do better? Well, yes. You can reduce the range further. You will first need to decide if you can get satisfactory convergence over that interval, with a reasonable number of terms. For example, if you look at the series for sin(x). Those terms are largest when x is large.

pi.^(1:2:25)./factorial(1:2:25)
ans =
       3.1416       5.1677       2.5502      0.59926     0.082146    0.0073704    0.0004663    2.1915e-05   7.9521e-07   2.2948e-08   5.3927e-10   1.0518e-11   1.7302e-13
(pi/2).^(1:2:25)./factorial(1:2:25)
ans =
       1.5708      0.64596     0.079693    0.0046818   0.00016044   3.5988e-06   5.6922e-08    6.688e-10   6.0669e-12   4.3771e-14   2.5714e-16   1.2539e-18   5.1565e-21

You just need to take a few more terms for the larger domain.

In fact, there are some simple tricks to further reduce the domain of interest. For example, if you do range reduction to +/-pi/4, the series will converge much faster yet. But you may choose a larger interval, just accepting a few more terms in the series. The tradeoff will then be between number of terms and complexity in the range reduction.