fork download
  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. // from http://r...content-available-to-author-only...e.org/wiki/Numerical_integration#C
  5. double int_leftrect(double from, double to, double n, double (*func)())
  6. {
  7. double h = (to-from)/n;
  8. double sum = 0.0, x;
  9. for(x=from; x <= (to-h); x += h)
  10. sum += func(x);
  11. return h*sum;
  12. }
  13.  
  14. double integral(double (*func)()) {
  15. return int_leftrect(0, 1, 10, func);
  16. }
  17.  
  18.  
  19. static double from;
  20. static double to;
  21. static double (*fn)();
  22. double scaled(double x) {
  23. return fn(from + x * (to - from));
  24. }
  25.  
  26. double integral_range(double (*func)(), double a, double b) {
  27. from = a;
  28. to = b;
  29. fn = func;
  30. return integral(scaled) * (b - a);
  31. }
  32.  
  33. double test_fn(double x) {
  34. double result = 2 * x;
  35. printf("TRACE: test_fn(%f) => %f\n", x, result);
  36. return result;
  37. }
  38.  
  39. int main(void) {
  40. double result = integral_range(test_fn, 3, 9);
  41. double expected = (9 * 9) - (3 * 3);
  42. printf("result of numerical integration: %f\n", result);
  43. printf("error of numerical integration: %f\n", fabs(result - expected));
  44. return 0;
  45. }
  46.  
Success #stdin #stdout 0s 2160KB
stdin
Standard input is empty
stdout
TRACE: test_fn(3.000000) => 6.000000
TRACE: test_fn(3.600000) => 7.200000
TRACE: test_fn(4.200000) => 8.400000
TRACE: test_fn(4.800000) => 9.600000
TRACE: test_fn(5.400000) => 10.800000
TRACE: test_fn(6.000000) => 12.000000
TRACE: test_fn(6.600000) => 13.200000
TRACE: test_fn(7.200000) => 14.400000
TRACE: test_fn(7.800000) => 15.600000
TRACE: test_fn(8.400000) => 16.800000
result of numerical integration: 68.400000
error of numerical integration: 3.600000