This week's giveaway is in the Java/Jakarta EE forum.We're giving away four copies of Java EE 8 High Performance and have Romain Manni-Bucau on-line!See welcome thread
Win a copy of Java EE 8 High Performance this week in the Java/Jakarta EE forum!
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Taylor Cosine Approximation (help!!!)

Ranch Hand
Posts: 115
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

Ranch Hand
Posts: 60
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.

Ranch Hand
Posts: 2458
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 ]

Wanderer
Sheriff
Posts: 18671
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 ]