Using Richardson Extrapolation with Finite Differences¶
Copyright (C) 2020 Andreas Kloeckner
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
from math import sin, cos
Here are a function and its derivative. We also choose a "center" about which we carry out our experiments:
f = sin
df = cos
x = 2.3
We then compare the accuracy of:
- First-order (right) differences
- First-order (right) differences with half the step size
- An estimate based on these two using Richardson extrapolation
against true
, the actual derivative
for k in range(3, 10):
h = 2**(-k)
fd1 = (f(x+2*h) - f(x))/(2*h)
fd2 = (f(x+h) - f(x))/h
richardson = (-1)*fd1 + 2*fd2
true = df(x)
print("Err FD1: %g\tErr FD: %g\tErr Rich: %g" % (
abs(true-fd1),
abs(true-fd2),
abs(true-richardson)))
Err FD1: 0.08581 Err FD: 0.0448122 Err Rich: 0.00381441 Err FD1: 0.0448122 Err FD: 0.022862 Err Rich: 0.000911846 Err FD1: 0.022862 Err FD: 0.0115423 Err Rich: 0.000222501 Err FD1: 0.0115423 Err FD: 0.00579859 Err Rich: 5.49282e-05 Err FD1: 0.00579859 Err FD: 0.00290612 Err Rich: 1.3644e-05 Err FD1: 0.00290612 Err FD: 0.00145476 Err Rich: 3.39995e-06 Err FD1: 0.00145476 Err FD: 0.000727804 Err Rich: 8.48602e-07