# Revision history [back]

To get it more convenient I wrapped numerical_integral for use with piecewise functions:

def numerical_integral_piecewise(f,a,b,**kwds):

"""
Returns a numerical integral from a piecewise function

f  - piecewise function

a  - lower bound of the interval

b  - upper bound of the interval

**kwds -  options passed to numerical_integral

EXAMPLES::

sage: f1(x) = 1
sage: f2(x) = 2
sage: f3(x) = 3
sage: f = piecewise([[(0,4),f1],[(4,6),f2],[(6,10),f3]])
sage: numerical_integral_piecewise(f,2,9)
15.0

if a (or b ) is outside the domain of f, the interval (a,b) is cut
to the lower bound (or upper bound) of the domain of f

sage: numerical_integral_piecewise(f,-2,20)
20.0

TODO
return an error estimate as numerical_integral does

"""

D = dict(f.list())
sum = 0
for k in D.keys():
if k <= a: continue
if k <= a and b <= k:
return numerical_integral(D[k],a,b,**kwds)
elif k <= a:
sum += numerical_integral(D[k],a,k,**kwds)
elif a <= k and k <= b:
sum += numerical_integral(D[k],k,k,**kwds)
elif k <= b <= k:
sum += numerical_integral(D[k],k,b,**kwds)
return sum

f1(x) = 1
f2(x) = 2
f3(x) = 3
f = piecewise([[(0,4),f1],[(4,6),f2],[(6,10),f3]])
numerical_integral_piecewise(f,-2,20)