fork download
  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. #define EPS 1e-6
  5. #define PI 3.14159
  6. static int j_;
  7.  
  8. float taylor_series(float x) {
  9. j_ = 1;
  10.  
  11. if (fabs(x) < EPS)
  12. return x;
  13.  
  14. float w = x * x;
  15. float y = x;
  16. float z = 1.0;
  17. float s = x;
  18.  
  19. for ( ; ; ) {
  20. y *= -w;
  21. z *= ++j_;
  22. z *= ++j_;
  23. float t = y / z;
  24. if (fabs(t) < EPS) break;
  25. s += t;
  26. }
  27.  
  28. return s;
  29. }
  30.  
  31. int main(void) {
  32. printf("%f\t", taylor_series(PI * 0.5));
  33. printf("%f\t", sin(PI * 0.5));
  34. printf("%d\n", j_);
  35. printf("%f\t", taylor_series(0.000123));
  36. printf("%f\t", sin(0.000123));
  37. printf("%d\n", j_);
  38. printf("%f\t", taylor_series(PI * 0.25));
  39. printf("%f\t", sin(PI * 0.25));
  40. printf("%d\n", j_);
  41. printf("%f\t", taylor_series(PI * 1.25));
  42. printf("%f\t", sin(PI * 1.25));
  43. printf("%d\n", j_);
  44. printf("%f\t", taylor_series(PI * 2.25));
  45. printf("%f\t", sin(PI * 2.25));
  46. printf("%d\n", j_);
  47. printf("%f\t", taylor_series(PI * 3.25));
  48. printf("%f\t", sin(PI * 3.25));
  49. printf("%d\n", j_);
  50. return 0;
  51. }
  52.  
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
1.000000	1.000000	13
0.000123	0.000123	3
0.707106	0.707106	9
-0.707105	-0.707104	21
0.707094	0.707103	29
-0.707314	-0.707101	35