lec9_derivatives

# lec9_derivatives - Computes the derivative of f wrt x with...

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

#Lecture 9 # Binary Searches # Numerical derivatives #------SLIDE 2-------- #Binary Search def BinSearch(S,N,Low,High): print Low,High if Low > High: print 'The number %i is not in the list.'%N return -1 Mid = int((High + Low)/2.0) if N == S[Mid]: print 'The number %i was found at position %i in the list ' % (N,Mid) return Mid elif N < S[Mid]: BinSearch(S,N,Low,Mid-1) else: BinSearch(S,N,Mid+1,High) import random S=[random.randint(0,100000) for i in range(10000) ] S.sort() #BinSearch(S,30,0,len(S)) # Numerically computing derivatives of a function using # various methods: Forward difference (fda), central difference (cda), # and backward difference (bda) from pylab import * # ##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): # ''' #

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.

Unformatted text preview: Computes the derivative of f wrt x with interval of h # using the backward difference approximation (fda). # ''' # return ( f(x) - f(x-h) )/h # # #def func(x): # return a*sin(b*x+c) # ##set up parameters for function #a,b,c=2.,3.,0. ##The x-value at which to compute the derivative #x=2 ##an initial h-value #h=0.02 ##Compute f' (df/dx) #fp=fda(func,2,h) # ##The actual df/dx #real=a*b*cos(b*x+c) # ##Try a range of h values to see how much better the approximation gets #hvalues=linspace(2e-13,2e-2,20) #errors= # #for h in hvalues: # fp=cda(func,2,h) # errors.append(abs(fp-real)) # #errors=array(errors) # #plot(hvalues,errors,'b-o') ##semilogx() #show() #print "The approximate value is:",fp #print "The true value is: ",real #print "The difference is: ",abs(real-fp) def f(x): return x**3 hvals= errs= h=1e-8 while h <= 1e-2: fp=cda(f,4,h) hvals.append(h) errs.append(abs(fp-48.0)) h*=10 plot(hvals,errs,'b-o') xlabel("h") ylabel('Error')...
View Full 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 / 2

lec9_derivatives - Computes the derivative of f wrt x with...

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

View Full Document
Ask a homework question - tutors are online