derivative function

double derivative(
  1. UnaryFunction<double> function,
  2. double x, {
  3. int derivative = 1,
  4. int accuracy = 2,
  5. double epsilon = 1e-5,
})

Returns the numerical derivative of the provided function function at x.

derivative must be a number between 1 and 6, higher derivatives are less stable. accuracy defines the number of coefficients used for the approximation. epsilon signifies the grid spacing (or step size).

Implementation

double derivative(
  UnaryFunction<double> function,
  double x, {
  int derivative = 1,
  int accuracy = 2,
  double epsilon = 1e-5,
}) {
  final accuracyToWeights = _centralFiniteDifferences.containsKey(derivative)
      ? _centralFiniteDifferences[derivative]!
      : throw ArgumentError.value(derivative, 'derivative',
          'Must be one of ${_centralFiniteDifferences.keys.join(', ')}');
  final weights = accuracyToWeights.containsKey(accuracy)
      ? accuracyToWeights[accuracy]!
      : throw ArgumentError.value(accuracy, 'accuracy',
          'Must be one of ${accuracyToWeights.keys.join(', ')}');
  final offset = accuracy ~/ 2;
  var result = 0.0;
  for (var i = 0; i < weights.length; i++) {
    result += weights[i] * function(x + (i - offset) * epsilon);
  }
  return result / pow(epsilon, derivative);
}