Comparison

Let us calculate the derivative using the various method up to the same accuracy. First use the five-point formula:

> restart:f:=x->ln(cos(x)):

> df:=D(f):ddf:=D(df):dddf:=D(ddf):ddddf:=D(dddf):dddddf:=D(ddddf):

> h:=0.1: df1:=1/(12*h)*(f(0.4-2*h)-8*f(0.4-h)+8*f(0.4+h)-f(0.4+2*h)): acterr:=abs(df1-df(0.4)): print(h,df1,acterr);

[Maple Math]

With the three-point formula, we need a smaller values of [Maple Math] :

> for i from 1 to 2 do h:=10.^(-i): df1b:=1/(2*h)*(f(0.4+h)-f(0.4-h)): acterrb:=abs(df1b-df(0.4)): print(h,df1b,acterrb);od:

[Maple Math]

[Maple Math]

Finally, a forward-difference scheme needs a much smaller value of [Maple Math] :

> for i from 1 to 5 do h:=10.^(-i): df1:=(f(0.4+h)-f(0.4))/h: acterr:=df1-df(0.4): print(h,df1,acterr); od:

[Maple Math]

[Maple Math]

[Maple Math]

[Maple Math]

[Maple Math]

This shows that the more-point formulae are more accurate, but the disadvantage is obviously that they are more complicated and therefore more difficult to implement in code. Moreover, because of the increase in the number of calculations needed, round-off errors become more prominent much quicker. For example, if we print the first value of [Maple Math] for which the actual error becomes larger then the maximum error:

> h:=0.001: df1:=1/(12*h)*(f(0.4-2*h)-8*f(0.4-h)+8*f(0.4+h)-f(0.4+2*h)): maxerr:=h^4*400/30:acterr:=abs(df1-df(0.4)): print(h,df1,maxerr,acterr);

[Maple Math]

> h:=10.^(-4): df1b:=1/(2*h)*(f(0.4+h)-f(0.4-h)): maxerr:=(h^2)*10./6:acterrb:=abs(df1b-df(0.4)): print(h,df1b,maxerr,acterrb);

[Maple Math]

> h:=10.^(-6): df1:=(f(0.4+h)-f(0.4))/h: maxerr:=h*3.5/2:acterr:=df1-df(0.4): print(h,df1,maxerr,acterr);

[Maple Math]

Therefore, some consideration needs to be given about which formula to use when.