C Board  

Go Back   C Board > General Programming Boards > C Programming

Reply
 
LinkBack Thread Tools Display Modes
Old 08-22-2009, 07:08 AM   #1
Registered User
 
Join Date: Aug 2009
Posts: 1
Unhappy (Term0 + Term1 - Term2 + Term3) How can I do the alternating plus minus?

I am working on a problem involving Taylor's Series of cosine x and sine x. (cosx = 1 - (x^2/2!) + (x^4/4!) - ...)
My only problem is how I can do the alternating plus minus on each term. This is the code I currently have in which I can't still figure out if it is right or wrong.

double cosine(double x)
{
int n, ctr;
double cos;

cos = 0;
n = 2*NUMBER_OF_TERMS;
ctr = NUMBER_OF_TERMS;
while(ctr > 0)
{
ctr--;
cos = cos + (RaiseTo(x, n)/factorial(n));
cos *= -1;
n -= 2;
}
return cos;
}

*Note: We were only allowed to use stdio.h as the header file.
potsky is offline   Reply With Quote
Old 08-22-2009, 09:04 AM   #2
Registered User
 
Join Date: Dec 2006
Location: Canada
Posts: 2,003
Code:
if (term % 2 == 0) {
x *= -1;
}
or, if you want to avoid a branch
Code:
double sign = 1;
while (...) {
     x *= sign;
     sign *= -1;
}
Not sure which one would be faster.
cyberfish is online now   Reply With Quote
Old 08-23-2009, 08:52 AM   #3
Mysterious C++ User
 
Elysia's Avatar
 
Join Date: Oct 2007
Posts: 14,783
x *= -1 is also the same as x = -x. The latter would probably be faster in terms of instructions, but a good compiler will probably optimize it.
However, be sure to read this: << !! Posting Code? Read this First !! >>
__________________
Using: Microsoft Windows™ 7 Professional (x64), Microsoft Visual Studio™ 2008 Team System
I dedicated my life to helping others. This is only a small sample of what they said:
"Thanks Elysia. You're a programming master! How the hell do you know every thing?"
Quoted... at least once.
Quote:
Originally Posted by cpjust
If C++ is 2 steps forward from C, then I'd say Java is 1 step forward and 2 steps back.
Elysia is offline   Reply With Quote
Reply

Tags
c programming, taylor's series, trigonometry

Thread Tools
Display Modes

Forum Jump


All times are GMT -6. The time now is 02:12 PM.


Powered by vBulletin® Version 3.8.1
Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.3.2

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22