Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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[1] <= a: continue
        if k[0] <= a and b <= k[1]:
            return numerical_integral(D[k],a,b,**kwds)[0]            
        elif k[0] <= a: 
            sum += numerical_integral(D[k],a,k[1],**kwds)[0]
        elif a <= k[0] and k[1] <= b:
            sum += numerical_integral(D[k],k[0],k[1],**kwds)[0]
        elif k[0] <= b <= k[1]:
            sum += numerical_integral(D[k],k[0],b,**kwds)[0]        
    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)