derivative function
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);
}