How this is a taylor function when there is no pow and no fact?

84 Views Asked by At
   long double s21_cos(double x) {
  long double result;
  if (s21_isnan(x) || s21_isinf(x)) {
    result = NAN;  
  } else {
    
    while (x > s21_M_PI) {
      x -= 2 * s21_M_PI;
    }
while (x < -s21_M_PI) {
  x += 2 * s21_M_PI;
}

result = 1.0;
long double term = 1.0;
long double sign = -1.0;
long double divident, divisor;
int iteration_n = 1;
printf("%Lf-", result);
for (int n = 2; s21_fabs(term) > 1e-20; n += 2) {
  divident=x*x;

  devisor=(n*(n-1));
  
  term = term * divident / devisor;
  if(sign<0)
  printf("+");
  else if(sign>0)printf("-"); 
  result += sign * term;


     sign *= -1.0;
      iteration_n++;
    }
  }
  return result;
}

It is working very good, but I am struggle to understand or find any info about this kind of taylor expansion. It uses no pow and no fact, but at every term it produces valid ratio as an answer although fractions numbers are reduced. For example in second iteration with input 2, original function term will be 16/24, but in this one it is 8/12 Here is an output of steps when input is 2:

1.000000-4.00000000000000000000/2.000000+8.00000000000000000000/12.000000-2.66666666666666666674/30.000000+0.35555555555555555557/56.000000-0.02539682539682539683/90.000000+0.00112874779541446208/132.000000-0.00003420447864892309/182.000000+0.00000075174678349282/240.000000-0.00000001252911305821/306.000000+0.00000000016377925566/380.000000-0.00000000000172399216/462.000000+0.00000000000001492634/552.000000-0.00000000000000010816/650.000000+0.00000000000000000067/756.000000

Please try to explain it to me, I been fighting this for 2 days.

1

There are 1 best solutions below

0
On

There is no pow nor fact because the definitions of these functions have been expanded inside the for loop. for (int n = 2; s21_fabs(term) > 1e-20; n += 2)

Here is the step routine: term = term * divident / devisor;

Despite the bad variable names what's going on is clear; at each step through the loop we multiply term by the next step of generation in Taylor series numerator and denominator; so term is always the correct value.