posted 11 years ago

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

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

posted 11 years ago

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.

Add the current and previous terms to obtain the result and save the current term in the 'previous' variable.

<a href="http://www.catb.org/~esr/faqs/smart-questions.html" target="_blank" rel="nofollow">How To Ask Smart Questions</a>

posted 11 years ago

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 ]

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 ]

posted 11 years ago

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 ]

[ October 13, 2006: Message edited by: Jim Yingst ]

"I'm not back." - Bill Harding, *Twister*