functions which take functions

Antti J Ylikoski antti.ylikoski at tkk.fi
Wed Apr 11 10:01:38 EDT 2012


On 9.4.2012 21:57, Kiuhnm wrote:
> Do you have some real or realistic (but easy and self-contained)
> examples when you had to define a (multi-statement) function and pass it
> to another function?
> Thank you.
>
> Kiuhnm

A function to numerically integrate another function comes as follows:

------------------------------------------------------

# Adaptive Simpson's integral.
#
# AJY 03-28-2012 from the Wikipedia.

import math

def simpsonsRule(f,a,b):
     c = (a+b) / 2.0
     h3 = abs(b-a) / 6.0
     return h3*(f(a) + 4.0*f(c) + f(b))

def recursiveASR(f,a,b,eps,whole):
     "Recursive implementation of adaptive Simpson's rule."
     c = (a+b) / 2.0
     left = simpsonsRule(f,a,c)
     right = simpsonsRule(f,c,b)
     if abs(left + right - whole) <= 15*eps:
         return left + right + (left + right - whole)/15.0
     return recursiveASR(f,a,c,eps/2.0,left) + \
         recursiveASR(f,c,b,eps/2.0,right)

def adaptiveSimpsonsRule(f,a,b,eps):
     "Calculate integral of f from a to b with max error of eps."
     return recursiveASR(f,a,b,eps,simpsonsRule(f,a,b))

def invx(x):
     return 1.0 / x


print("Simpson integral : ", \
     adaptiveSimpsonsRule(invx,1.0,2.0,.000000001))
print("Exact value ln(2): ", math.log(2.0))
print("Value of epsilon : ", .000000001)


------------------------------------------------------------


kind regards, Antti J Ylikoski
Helsinki, Finland, the EU
http://www.tkk.fi/~ajy/
http://www.tkk.fi/~ajy/diss.pdf
antti.ylikoski at gmail.com



More information about the Python-list mailing list