Help please solve the problem. It is necessary to calculate the sum of the Taylor series with the decree. accuracy and with maximum accuracy (n is the maximum value for which the calculation of the formula is correct).

#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <math.h> double f(int n, int x) { double res; res = pow(x, 2*n + 1); res *= pow(-1,n); res *= (double)powf(-0.5, n); return res; } factorial(n) { int r, s; s = 2 * n + 1; for (r = 1; s > 1; r *= (s--)) ; return r; } int main() { float e; double sum = 0; int n = 0, x=0; double previous, current, S; scanf("%d\n", &x); scanf("%d\n", &n); scanf_s("%f", &e); current = f(n,x)/factorial(n); sum += current; n++; do { previous = current; current = f(n,x); sum += current; n++; } while (abs(current - previous) > e); printf("sum = %f\n", sum); _getch(); return 0; } 
  • and what's the problem? - Komdosh
  • And, well, in general, you have N entered by the user, but it must be 0 initially. - Komdosh
  • I have a result, it turns out some left number - Sanya. From
  • And what is this mess of scanf and scanf_s? What is the idea? - AnT
  • The C language does not allow for a long time to omit the int type. int factorial(int n) , not factorial(n) . And in general, the task of finding the sum of a Taylor series is primarily the problem of the correct methods of summing up floating numbers: either from smaller to larger, or Kahan, or something else. For some reason this was forgotten ... - AnT

1 answer 1

You can either ask n or precision, but not at the same time :)

The series is alternating, so that the accuracy is reached as soon as the dropped member in absolute value is less than this accuracy itself.

 double sum(double x, double eps) { double s = x, t = x; x *= x; for(int n = 1; fabs(t) > eps; ++n) { s += t *= -x/(2.*n*(2.*n+1)); } return s; } 

This is the easiest way to calculate it. We use the ratio of two neighboring members of the series to calculate the next term based on the previous one.

I use exactly the accuracy . I think, to rewrite for the number of members of the series - is it not difficult?

Here you can see a comparison with the real sine ...

  • Harry, can I insert what you wrote in my code and show it? And then I'm afraid that again I will do some kind of garbage and nothing will work, please - Sanya. From
  • Not. I will not do such trifles for you. It helps, and not do the finished work. I deliberately changed the answer a little - not 100% for your condition - so that it was exactly help, and you put your part of the work in order to understand how it works. You are new to the site, so a small explanation - if you just wrote a statement of the problem, the question would be closed very quickly (with the wording, the Learning assignments are allowed as questions only if you tried to solve them yourself ). But you wrote something - so I tried to push you to the right decision. But don't write for you .. - Harry