# [Edu-sig] Re: More on intro to Python (today's 3 hr training)

Kirby Urner urnerk at qwest.net
Tue Mar 29 17:05:00 CEST 2005

```> Sorry for being picky, but while your derivative factory
> function follows the mathematical definition, it is not the
> "best" way to do it numerically.  The preferred way is:
>
>   def derivative(f):
>       """
>       Factory function:  accepts a function, returns a closure
>       """
>       def df(x, h=1e-8):
>           return (f(x + h/2) - f(x - h/2))/h
>       return df
>
> This is best seen by doing a graph (say a parabola) and drawing
> the derivative with a large "h" using both methods near a local
> minimum.
>
> André

Hey good to know André and thanks for being picky.

Fresh from yesterday's example, I posted something about *integration* to a
community college math teacher list last night, which I think is maybe

===

def integrate(f,a,b,h=1e-3):
"""
Definite integral with discrete h
Accepts whatever function f,
runs x from a to b using increments h
"""
x = a
sum = 0
while x <= b:
sum += h*(f(x-h)+f(x+h))/2.0 # average f(x)*h
x += h
return sum

>>> def g(x):  return pow(x,2)  # so this is what we want to investigate

>>> integrate(g,0,3,h=1e-4) # h = 0.0001, close to 9
8.9995500350040558

>>> integrate(f,0,3,h=1e-6) # h = 0.000001, even closer to 9
8.9999954998916039

def defintegral(intexp, a, b):
return intexp(b) - intexp(a)

>>> def intg(x):  return (1./3)*pow(x,3)  # limit function

>>> defintegral(intg, 0, 3)  # exactly 9
9.0

===

The post (which includes the above but is longer) hasn't showed up in the
Math Forum archives yet, or I'd add a link for the record.  Maybe later.

Kirby

```