avoid catastrophic cancellation in divided differences #858
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There's a catastrophic cancellation happening in the computation of the divided differences matrix, as @antoine-levitt told me about on Slack. The problem is when we don't approximate the divided difference by the derivative of the mean, and the values are still close to eachother. Currently the threshold is set to be
abs(x-y) < sqrt(eps(T))
. Then the error of (f(x)-f(y))/(x-y) will be roughly eps(T)/sqrt(eps(T)) = sqrt(eps(T)), which is pretty bad. Things become catastrophic when we look at the second-order divided difference, then the error is roughly eps(T)/(sqrt(eps(T)) * sqrt(eps(T))) = 1, and the third order that gives us error 1/sqrt(eps(T)).Luckily there's a simple fix: the error incurred by using the derivative of the mean is roughly tol^2, so we can use it for x,y that are further apart instead of the naïve formula. Equating both errors gives us eps(T) / tol = tol^2 => tol = cbrt(eps(T)). Substituting that into the formula for the errors of the second-order divided difference gives us eps(T)/ (tol * tol_2) = tol_2^2 => tol_2 = eps(T)^(2/9), and doing the same for the third order gives us eps(T)^(4/27).