__author__ = "Marie E. Rognes (meg@simula.no)" __copyright__ = "Copyright (C) 2012 Marie Rognes" __license__ = "GNU LGPL version 3 or any later version" import math # Define e_h as a function of f, the derivative of f: df, x and h def e_h(f, df, x, h): return df(x) - (f(x+h) - f(x))/h # Define E_h as a function of f, the derivative of f: df, x and h def E_h(f, df, x, h): return df(x) - (f(x+h) - f(x-h))/(2*h) # Define a function that prints a pretty LaTeX table of the results def print_table(f, df, approx, x, hs, name): print "\\begin{table}[h]" print "\\begin{tabular}{lllll}" print "\\toprule" title = "$%s$ & $%s$ & $%s$ & $%s$ & $%s$ \\\\" \ % ("h", name, "%s/h" % name, "|%s|/h" % name, "|%s|/h^2" % name) print title print "\\midrule" for h in hs: d_h = approx(f, df, x, h) print "%.4f&" % h, print "%.4f& " % d_h, print "%.4f&" % (d_h/h), print "%.4f&" % (abs(d_h)/h), print "%.4f \\\\" % (abs(d_h)/(h**2)) print "\\bottomrule" print "\\end{tabular}" print "\\end{table}" # Define the sample function f = e^x def f(x): return math.exp(x) # Define the derivative of f: df = e^x def df(x): return math.exp(x) # Define a series of h's: hs = [1.0/n for n in (2, 4, 8)] # Let x = 1. print "f = e^x:" print_table(f, df, e_h, x, hs, "e_h") print_table(f, df, E_h, x, hs, "E_h") # Define sample function g = ln(x) def g(x): return math.log(x) # Define derivative of g: dg = 1.0/x def dg(x): return 1.0/x print print "g = ln(x):" print_table(g, dg, e_h, x, hs, "e_h") print_table(g, dg, E_h, x, hs, "E_h")