1 Replies - 2138 Views - Last Post: 04 February 2012 - 08:11 AM

#1 KYA   User is offline

  • Wubba lubba dub dub!
  • member icon

Reputation: 3202
  • View blog
  • Posts: 19,235
  • Joined: 14-September 07

Approximate cos(x) using a Taylor Series

Posted 24 March 2010 - 04:11 PM

Description: Implement when you need cosine(x). Precision argument provided by default to alleviate any need for the user to specify a 2nd parameter. More precision = better approximation. Example implementation and comparison with math.h's cosine function. Approximates cosine (x) using the Taylor Series for cos(x) = (-1)^n*x^(2n)/(2n)!
//feel free to implement this w/ recursion 
double factorial(int num){
	double fact = 1;
	for(int i = 1; i <= num; i++){
		fact *= i; 
	}
	return fact;
}

//Taylor series cos(x) = (-1)^n*x^(2n)/(2n)!
double taylorCosine(double num, double precision = 20){
	double value = 0;
	for(int n = 0; n < precision; n++){
		value += pow(-1.0, n) * pow(num, 2*n)/factorial(2*n);
	}
	return value;
}

/* 
	What you'll see:
	
	0.540302                        0.540302
	-0.416147                       -0.416147
	-0.989992                       -0.989992
	-0.653644                       -0.653644
	0.283662                        0.283662
	0.96017                         0.96017
	0.753902                        0.753902
	-0.1455                         -0.1455
	-0.91113                        -0.91113
	-0.839072                       -0.839072

	Requires +1 to precision as 19 would give -0.839071 for the last number
*/
int main(){
	for(int i = 1; i <= 10; i++){
		//math.h's cosine							my cosine
		cout << cos((double) i) << "      ttt" << taylorCosine((double)i) << endl;	
	}
    return 0;
}


Is This A Good Question/Topic? 0
  • +

Replies To: Approximate cos(x) using a Taylor Series

#2 Karel-Lodewijk   User is offline

  • D.I.C Addict
  • member icon

Reputation: 454
  • View blog
  • Posts: 864
  • Joined: 17-March 11

Re: Approximate cos(x) using a Taylor Series

Posted 04 February 2012 - 08:11 AM

For anyone looking at this to create a real, sound implementation. Know that Taylor series rapidly loses precision the further from the point they are developed, 0 in this case. You should bring your arc at least within the [0, 2Pi] range. And using symmetries, you can bring your arc into the [-Pi/2, Pi/2] range and further to the [0, Pi/2] range. And by using the sinus Taylor series when appropriate, you could bring it to the [0, Pi/4] range. Draw it on a geometric cirkel and you'll see what I'm talking about. To further improve precision/efficiency, you could create a table of pre-calculated high precision sin/cos values on that reduced range, pick the arc closest to the one you need and develop a Taylor series from that point.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1