fork download
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<math.h>
  4.  
  5. typedef double (*FUNC)(double);
  6.  
  7. double integ(FUNC f, const double a, const double b, const int n){
  8. int i;
  9. const double dx = (b - a)/n;
  10. double total = 0.0;
  11.  
  12. for (i = 0; i < n; i++){
  13. const double x = -(a + (i+0.5)*dx);
  14. total += f(x)*dx;
  15. }
  16.  
  17. return total;
  18. }
  19.  
  20. int main(void){
  21. const double a = 0;
  22. const double b = 0.49;
  23. const double sval = 1-exp(-b);
  24. int i;
  25.  
  26. printf("Integration of exp(-x) for [%.2f, %.2f] and errors\n",a, b);
  27. for(i = 0; i < 7; i++){
  28. const int div = (int)pow(10, i);
  29. const double xi = integ(exp, a, b, div);
  30. const double err = sval - xi;
  31. printf("%7d %.15f %.15e\n", div, xi, err);
  32. }
  33.  
  34. printf("strict value = %.15f\n", sval);
  35.  
  36. return 0;
  37. }
  38.  
Success #stdin #stdout 0.02s 5388KB
stdin
Standard input is empty
stdout
Integration of exp(-x) for [0.00, 0.49] and errors
      1 0.383525223738515 3.848382077068502e-03
     10 0.387334855028139 3.875078744475235e-05
    100 0.387373218280844 3.875347402426677e-07
   1000 0.387373601940234 3.875350207405148e-09
  10000 0.387373605776830 3.875394449792680e-11
 100000 0.387373605815202 3.820277427735164e-13
1000000 0.387373605815561 2.309263891220326e-14
strict value = 0.387373605815584