#!/usr/bin/python # ---------------------------------------------------------------- # John Kerl # kerl.john.r@gmail.com # 2005-07-06 # # Plots a function along with its estimated and exact first and second # derivatives. # ---------------------------------------------------------------- # This software is released under the terms of the GNU GPL. # Please see LICENSE.txt in the same directory as this file. # ================================================================ from __future__ import division # 1/2 = 0.5, not 0. from math import * # ---------------------------------------------------------------- def f(x): #return sin(x) #return exp(x) return (1 + x**2)**0.5 def fp(x): #return cos(x) #return exp(x) return x / ((1 + x**2)**0.5) def fpp(x): #return -sin(x) #return exp(x) return 1 / ((1 + x**2)**1.5) # ---------------------------------------------------------------- xlo = -4.0 xhi = 4.0 nx = 800 dx = (xhi - xlo) / nx x = xlo for i in range(0, nx): # Exact y = f(x) yp = fp(x) ypp = fpp(x) # Estimated h = 0.5 * dx xf = x + h xb = x - h ypest = (f(xf) - f(xb)) / (2.0*h) yppest = (f(xf) - 2*f(x) + f(xb)) / (h*h) diffp = yp - ypest diffpp = ypp - yppest #print "%11.6f %11.6f %11.6f %11.6f %11.6f %11.6f" % (x, y, yp, ypest, ypp, yppest) print "%11.6f %11.6f %11.6f %11.6f %8.2e %11.6f %11.6f %8.2e" % (x, y, yp, ypest, diffp, ypp, yppest, diffpp) x += dx