Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Script for series expansion of sine
Date: Thu, 23 Apr 2009 02:57:01 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 24
Message-ID: <gsoldt$178$1@fred.mathworks.com>
References: <gsohrh$27i$1@fred.mathworks.com> <gsok1b$ruu$1@fred.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: webapp-02-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1240455421 1256 172.30.248.37 (23 Apr 2009 02:57:01 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Thu, 23 Apr 2009 02:57:01 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1187260
Xref: news.mathworks.com comp.soft-sys.matlab:534848


"Roger Stafford" <ellieandrogerxyzzy@mindspring.com.invalid> wrote in message <gsok1b$ruu$1@fred.mathworks.com>...
> "Sean " <el_sean@yahoo.com> wrote in message <gsohrh$27i$1@fred.mathworks.com>...
> > I'm trying to write a script to calculate the series expansion of sine with the inputs x (argument) and n.  Here's what I've thrown together so far:
> > 
> > % SINESERIES:  computes sin(x) from series expansion.
> > % A script to evaluate the series expansion of sine with the formula:
> > % sin(x) = x-(x^3/3!)+(x^5/5!)-... 
> > x = input('Enter the argument x:  ');
> > n = input('Enter the interval n:  ');
> > N = 1:1:n;     % Creates row vector with n elements, 1 at a time.
> > k = 2*N-1;    % For convenience with prod() function
> > j = N-1;        % For cleanup.
> > sinseries = ((-1).^(j)).*((x.^(k))./(prod(k)))
> > sum(sinseries)

  I should have pointed out that there are more efficient ways of carrying out that computation.  Suppose n = 5.  You could do the computation this way:

 s = x*(1-x^2/(2*3)*(1-x^2/(4*5)*(1-x^2/(6*7)*(1-x^2/(8*9)))));

Moreover you can easily devise a for-loop that accomplishes this calculation in the same sequence of operations for a general n.  You would have to work from the high end and go backwards.  It obviously involves far fewer multiplications and divisions and is more accurate numerically in the bargain.  In spite of the for-loop overhead, this method is bound to be faster for sufficiently large n, since it is an order n algorithm whereas your original one is order n^2.

  Another observation:  Don't try this with values of x substantially larger than 1 unless you have set n very high.  High values of x will cause the series to converge very slowly at first and only when the ratio x/k grows substantially smaller than 1 does it begin to converge at a decent rate.  In the actual computation of the sine function, things are done in a very different manner than this.

Roger Stafford