Skip to content

Numerical Tools

codechembook.numericalTools

integrateRange(y, x, limits, method='trapezoid')

Integrate a numeric function over a range less than the full extent of the function.

Parameters:

Name Type Description Default
y ndarray

y-values for integration.

required
x ndarray

x-values for integration. (need not be evenly spaced)

required
limits list of numeric

Lower and upper limits of integration.

required
method str

which approach to use (default: 'trapezoid', options: 'rectangle', 'simpson').

'trapezoid'

Returns:

Name Type Description
float

Value of the integral.

Source code in src/codechembook/numericalTools.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def integrateRange(y, x, limits, method='trapezoid'):
    '''
    Integrate a numeric function over a range less than the full extent of
    the function.

    Args:
        y (ndarray): y-values for integration.
        x (ndarray): x-values for integration. (need not be evenly spaced)
        limits (list of numeric): Lower and upper limits of integration.
        method (str, optional): which approach to use (default: 'trapezoid', options: 'rectangle', 'simpson').

    Returns:
        float: Value of the integral.
    '''

    # Sort the limits so they are in the order [lower, upper]
    limits.sort()

    # Find the indicies of the range that we want to integrate
    int_range = (x >= limits[0]) & (x < limits[1])

    # Decide which integration method the user wants
    if method == 'simpson':
        return spi.simpson(y[int_range], x[int_range])

    elif method == 'rectangle':
        return np.sum(y[int_range[:-1]] * (x[int_range[1:]] - x[int_range[:-1]]))

    else:
        # Maybe the user typed something wrong into the method keyword
        if method != 'trapezoid':
            print('Invalid method specified, defaulting to trapezoid')
            print('Please choose rectangle, trapezoid, or simpson')
        return spi.trapezoid(y[int_range], x[int_range])