cloopsfor-looptaylor-series

I do nor know how to fix code to get a result


I made a code and do not understand how to force it work. I`m sure that problem is somewhere in loop but do not know how to fix it. Here is a task: Compose a program for approximate calculation of the value of the function Y(x) in points 0 < | x | < 1 using the Taylor series expansion of S(x). Find the approximate value of the function with an error less than ε < 0.0001. Enter the values of x and ε from the keyboard. Display the exact value of Y(x), the approximate value of S(x) found, and the resulting error | S(x) – Y(x) |.

There is my code:

`#include <stdio.h>
#include <math.h>

int main(){
double x, E;
printf("x: ");
scanf("%lf", &x);
printf("E: ");
scanf("%lf", &E);
double Yx = sin(x);
double Sx = 0;
if(fabs(x) >= 1 && E >= 1e-4)
    printf("Change x and e");
else if(E >= 1e-4)
    printf("Change e");
else if(fabs(x) >= 1)
    printf("Change x");
else{
for(int k = 0;;k++) {
double f2 = 2 * k + 1;
for(int l = 1; l <= k; l++)
f2 = f2 * l;
double S2 = pow(-1, k) * (pow(x, (2 * k + 1)) / f2);
if(fabs(Sx-Yx) <= E)
break;
Sx= Sx + S2;
}
printf(" Y(x) = %lf\n", Yx);
printf(" S(x) = %lf\n", Sx);
printf(" |S(x)-Y(x)| = %lf \n", fabs(Yx-Sx));
return 0;
  }
 }`

Solution

  • This code does not compute the desired factorial correctly:

    double f2 = 2 * k + 1;
    for(int l = 1; l <= k; l++)
    f2 = f2 * l;
    

    In the future, step through your program in a debugger or insert printf statements to show the values of the variables. Printing the value of f2 after that loop would have revealed it is not the desired value.