Advertisement
luizaspan

[PROVA FSC_COMP] Integração Numérica (Trapézio Otimizado)

Nov 3rd, 2015
396
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.82 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. #define del 1e-5
  5.  
  6. double f(double x)
  7. {
  8.     return 1/x; // função a ser integrada
  9. }
  10.  
  11. int main(void)
  12. {
  13.     int N = 10;
  14.     double h, I, Iold, eps;
  15.  
  16.     // ------------------------- I_1 -------------------------
  17.  
  18.     int i;
  19.     double soma=0.0f,a=0.1;
  20.  
  21.     h=(1.0-a)/N;
  22.  
  23.     for (i=0;i<N;i++)
  24.     {
  25.         double x1 = a + h*i, x2= a + h*(i+1);
  26.         soma += (h/2)*(f(x1) + f(x2));
  27.     }
  28.  
  29.     I = soma;
  30.  
  31.     // ------------------------- END -------------------------
  32.  
  33.     do {
  34.         Iold = I;
  35.         N = 2*N;
  36.         h = h/2; // otimizando!
  37.  
  38.         double soma = 0; // importante zerar somaaa!!!
  39.  
  40.         for(i = 1; i < N; i += 2)
  41.         {
  42.             soma += f(a + i*h);
  43.         }
  44.  
  45.         I = 0.5*Iold + h*soma;
  46.  
  47.         eps = 1.0/3 * fabs(I - Iold);
  48.  
  49.         printf("%d %e\n", N, eps);
  50.     } while (eps > del);
  51.  
  52.     return 0;
  53. }
  54.  
  55. // erro = 1/12 * h^2 * [f'(a) - f'(b)]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement