integrate function

num integrate(
  1. num func(
    1. num x
    ),
  2. num lowerLimit,
  3. num upperLimit,
  4. {double dxMax = 0.1}
)

Returns the definite integral of func over the interval (lowerLimit,upperLimit) using the trapezoidal approximation.

Depending on the function the integral might not be defined and convergence is not guaranteed for dxMax -> 0.

The maximum number of integration sub-intervals is 10000.

Implementation

num integrate(
  num Function(num x) func,
  num lowerLimit,
  num upperLimit, {
  double dxMax = 0.1,
}) {
  dxMax = dxMax.abs();
  final interval = upperLimit - lowerLimit;

  var n0 = (interval.abs() / dxMax).ceil();
  n0 = (n0 > 100000) ? 100000 : n0;
  final n = (n0 < 10) ? 10 : n0;

  // Integration sub-interval:
  final dx = interval / n;

  var integral = 0.5 * (func(lowerLimit) + func(upperLimit));
  for (var i = 1; i < n; ++i) {
    integral += func(lowerLimit + i * dx);
  }
  return integral * dx;
}