Monday, May 24, 2010

Plllllllllllzzzzzzzzzzzzzz help i need a c++ code that calculate the cos of x without using the power,cos.....

or any other function

Plllllllllllzzzzzzzzzzzzzz help i need a c++ code that calculate the cos of x without using the power,cos.....
This is actually not terribly difficult. You need to use the taylor expansion of the cosine function:


cos(x)=1-x^2/2!+x^4/4!-x^6/6!...to infinity, or:


sum from n=0 to inf of [(-1)^n*x^2n]/(2n)!





The true cosine of x would require to sum those terms to infinity, but for a computer you only need a few of the first ones to get a good enough approximation (for the most part, 10 should be plenty)





This looks like a homework assignment, so I won't write this in C++ for you, but I'll tell you how to do it. A simple program (not in C++) would go something like this:





x=1.5705 (this would be the x you are taking a cos of)





ans=1;


xnum=1;


sign=1;





for i from 1 to 10


__sign=sign*(-1);


__xnum=x*x*xnum;


__xden=1;


__dummy=2*i;


__for j from 1 to dummy


____xden=xden*j;


__end


__ans=ans+sign*(xnum/xden)


end





ans;





This requires that x be in radians. Each iteration of the external loop calculates a term in the infinite series, with the variable "sign" keeping track of whether the term should be positive or negative, the variable "xnum" tracks and calculates what the numerator of the term should be (x^2n), and the variable "xden" calculates the value in the denominator (2n!) for each term. At the end of the external loop these terms are combined with the previous value of "ans" to give you a better approximation. If you want more accuracy, you simply need to increase the number of times the external for loop executes.
Reply:use any infinite series, just make sure that you go to say, 10 significant digits...
Reply:?????????????


No comments:

Post a Comment