Why do we take the absolute value of term to find the cos series when will the term even be less than 0.0001 please explain if possible with example?
X = (22.0/7.0) * (Theta/180.0);
CosX = 1.0;
Term = 1.0;
i = 1;
while(fabs(Term)>=0.0001){
Term = (-1) * Term * X*X/((2*i-1)*2*i);
CosX = CosX Term;
i ;
}
CodePudding user response:
The sign of the terms alternate: the Taylor series of cosine is
1 - x^2/2! x^4/4! - x^6/6! ...
// ^ ^ ^
Then, the first non-trivial term for |x| > 0 is negative and clearly < 0.0001.
Another way to handle this is to unroll twice using only positive terms.
do {
Term = Term * X*X/((2*i-1)*2*i);
CosX = CosX - Term;
i ;
Term = Term * X*X/((2*i-1)*2*i);
CosX = CosX Term;
i ;
} while (Term > 0.0001);
CodePudding user response:
The idea of the loop condition is to continue approximation until the last change is very small, indicating being close to the precise value. Of course such a condition, one way or another, is needed, because the correct value is unknown and because arriving at it (even if known) would be taking inefficient time.
However "small" for a change, a delta, is the kind of small where -10 is larger than 2. I.e. if the last change was by a big but negative step, the loop should continue. Only when the change does not move a lot anymore in either direction (positive or negative) a reasonable approximation can be assumed.
Wether that is done via taking the absolute value of the change for comparison, or do two checks (one against a small positive change and one against a large negative one - where the largest one is of course very close to 0) does not matter.
CodePudding user response:
We do not have to use fabs
in the while
loop
We can check both conditions (negative && positive) instead:
while( wTerm >= 0.0001 || wTerm <= -0.0001){