Advertisement
desdemona

taylor

Feb 23rd, 2013
238
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.18 KB | None | 0 0
  1.  #include <stdio.h>
  2. #include <math.h>
  3.  
  4. int sgn(double x) {
  5.         if (x > 0)
  6.                 return 1;
  7.         else if (x < 0)
  8.                 return -1;
  9.         else
  10.                 return 0;
  11. }
  12.  
  13. double arctg(double x) {
  14.         double suma, wyraz;
  15.         int znak, n = 1;
  16.  
  17.         if (fabs(x) <= 1) {
  18.                 suma = 0;
  19.                 wyraz = x;
  20.                 znak = -1;
  21.  
  22.                 do {
  23.                         n=1;
  24.                         suma = suma + wyraz;
  25.                         wyraz = wyraz * znak * ((2 * n - 1) * x * x) / (2 * n + 1);
  26.                         znak = znak * (-1);
  27.                         n++;
  28.                 } while (abs(suma) > 1e-7);
  29.  
  30.                 return suma;
  31.         }
  32.  
  33.         else {
  34.                 suma = sgn(x) * (M_PI / 2);
  35.                 wyraz = -1 / x;
  36.                 znak = -1;
  37.  
  38.                 do {
  39.                         suma = suma + wyraz;
  40.                         wyraz = wyraz * znak * 1 / (((2 * n - 1) * x * x) / (2 * n + 1));
  41.                         znak = znak * (-1);
  42.                         n++;
  43.                 } while (fabs(wyraz) > 1e-7);
  44.                 return suma;
  45.         }
  46.  
  47. }
  48.  
  49. int main(void) {
  50.         double x = -10;
  51.  
  52.         printf("%10s %10s %10s %10s\n","x","arctg(x)","atan(x)","error");
  53.  
  54.         while (x <= 10) {
  55.                 printf("%10f %3.7f %3.7f %3.7f\n", x, arctg(x), atan(x), fabs(arctg(x) - atan(x)) / fabs(atan(x)));
  56.                 x += 1;
  57.         }
  58.  
  59.         getchar();
  60.         getchar();
  61.         return 0;
  62. }
  63.  
  64.  
  65.  
  66. double arctg(double x) {
  67.     assert(fabs(x) <= 1.0);
  68.  
  69.     if (fabs(x) <= 1) {
  70.         // Zeby nie liczyc tego w kolko
  71.         double xsqr = x*x;
  72.  
  73.         // Licznik
  74.         double num = x;
  75.  
  76.         // Mianownik
  77.         double denom = 1.0;
  78.  
  79.         // Pomocnicza zmienna, dzieki niej
  80.         // oceniamy kiedy sie zatrzymaฤ‡
  81.         double tmp = 0.0;
  82.  
  83.         // Suma
  84.         double sum = 0.0;
  85.  
  86.         do {
  87.             tmp = num/denom;
  88.             sum += tmp;
  89.             num *= -xsqr;
  90.             denom += 2.0;
  91.         }while(fabs(tmp)>1e-5);
  92.  
  93.         return sum;
  94.     }else {
  95.         return 0.0;
  96.     }
  97. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement