nder2("tan", /2.01)
✜
which returns 16374.242. The absolute error is about 1.01E-4, and the relative error is 6.19E-9.
The table below demonstrates the improvement in the derivative estimate as h decreases, for tan(x)
evaluated at x = 1.
3E-73.4255 1851E-7
2E-83.4255 1881E-6
9.5E-83.4255 1882 1E-5
9.356E-63.4255 1891 51E-4
9.359E-43.4255 2827 1351E-3
(none)3.4264 6416 0091E-2
difference in f'(x)f'(x)h
nder2() starts with h = 0.01, and divides h by 10 for each new estimate, so that the steps for h are
1E-2, 1E-3, ... 1E-14. Since the difference in f'(x) starts increasing at h = 1E-7, nder2() returns the
value for h = 1E-6.
More accurate results with Ridders' method: nder1()
Ridders' method (Advances in Engineering Software, vol. 4, no. 2, 1982) is based on extrapolating the
central difference formula to h=0. This method also has the important advantage that it returns an
estimate of the error, as well. This program, nder2(), implements the algorithm:
nder1(ff,xx,hh)
func
©("f",x,"auto" or h), return {f'(x),err}
©Based on Ridders' algorithm
©6jun00/dburkett@infinet.com
local con,con2,big,ntab,safe,i,j,err,errt,fac,amat,dest,fphh,fmhh,ffun,h1,d3
© Initialize constants
1.4→con
con*con→con2
1900→big
10→ntab
2→safe
newmat(ntab,ntab)→amat
© Build function strings
ff&"(xx+hh)"→fphh
ff&"(xx-hh)"→fmhh
ff&"(xx)"→ffun
© Find starting hh if hh="auto"
if hh="auto" then
if xx=0 then: .01→h1
else: xx/1000→h1
endif
expr(ff&"(xx+h1)")-2*expr(ffun)+expr(ff&"(xx-h1)")→d3
if d3=0: .01→d3
6 - 29