• Post Reply Bookmark Topic Watch Topic
  • New Topic

Taylor Cosine Approximation (help!!!)  RSS feed

 
John Lockheart
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have this code inside a seperate method :
for (i= 0; i <=terms; i++){
value = (((Math.pow(-1, i)) * (Math.pow(radAngle,(2*i)))) / (factorial(2 * i)));
} return value;

But i can't figure out how to add each term together, the 2nd term has to equal the 1st term plus the 2nd term (kinda like the fibbonacci sequence). And the 3rd term has to equal 2nd plus the 3rd and so on. Can anyone help?

ex) Term1 = 1, term2 = -0.5, term3 = 0.4416 Answer = 1, 0.5, 0.9416
 
Mark Van Tuyl
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Create a variable to hold the previous term and initialize it to zero.
Add the current and previous terms to obtain the result and save the current term in the 'previous' variable.
 
Bauke Scholtz
Ranch Hand
Posts: 2458
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You mean a function like the 2nd one here? http://en.wikipedia.org/wiki/Taylor_series (sin(x) ~ x - x^3/3! + x^5/5! etc)

Use a placeholder int 1 which switches negative or positive during every loop and multiply with it. Here is an example for this function:


[ October 13, 2006: Message edited by: Bauke Scholtz ]
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Once you've got some code which works, it may be worthwhile to spend a bit of time finding ways to make this a little more efficient. (Though whether or not this is necessary may depend on what sort of course this is homework for.) Two points which stick out to me are:
  • Calling Math.pow() is a rather heavyhanded way to get the power. You can do this yourself with simple multiplication in a loop - and you've already got a loop
  • There's also no need to calculate the factorial() stuff every time you evaluate the Taylor series. You can evaluate the Talor coefficients just once at the beginning, and store them in an array. (A static block is a good way to do this when the class first loads.) Then later calls to this method will simply access the array to get the coefficients, rather than recalculating them.

  • [ October 13, 2006: Message edited by: Jim Yingst ]
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!