hw4_soln

# Hw4_soln - from pylab import def cda(x,h return f(x h-f(x-h(2*h#Central difference approximation def cda(f,x,h return(f(x h-f(x-h(2*h#Forward

This preview shows pages 1–2. Sign up to view the full content.

from pylab import * def cda(x,h): return ( f(x+h)-f(x-h))/(2*h) ##Central difference approximation def cda(f,x,h): return (f(x+h)-f(x-h))/(2*h) # ##Forward difference approximation def fda(f,x,h): ''' Computes the derivative of f wrt x with interval of h using the forward difference approximation (fda). ''' return ( f(x+h) - f(x) )/h # ##Backward difference approximation def bda(f,x,h): ''' Computes the derivative of f wrt x with interval of h using the backward difference approximation (fda). ''' return ( f(x) - f(x-h) )/h x=linspace(0,5,100) def f(x): return x*sin(2*x) def dfdx(x): return 2*x*cos(2*x)+sin(2*x) hvals=[1e-3,1e-2,1e-1,1] x=linspace(0,5,100) subplot(221) hval=hvals[0] l1=plot(x,dfdx(x),label='Exact') l2=plot(x,cda(f,x,hval),label='CDA') plot(x,fda(f,x,hval),label='FDA') plot(x,bda(f,x,hval),label='BDA') ## NOTE the fancy legend for a subplot figure! legend(loc='right',bbox_to_anchor=(2.1,1.15),ncol=4) text(0.2,6,'h=%2.1e'%hval) xlabel('x') ylabel('\$(d/dx)x*sin(2x)\$') subplot(222)

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

## This note was uploaded on 10/05/2010 for the course PHYS phy503 taught by Professor Gladden during the Spring '09 term at Ole Miss.

### Page1 / 3

Hw4_soln - from pylab import def cda(x,h return f(x h-f(x-h(2*h#Central difference approximation def cda(f,x,h return(f(x h-f(x-h(2*h#Forward

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online