integrator.py

Created by asness

Created on May 11, 2019

1013 Bytes


def wrap_1_var_func(funcOrConstant):
    if callable(funcOrConstant):
        # it's a function: leave it alone
        return funcOrConstant
    else:
        # it's a constant: wrap it
        return lambda x: funcOrConstant

def quad2(func, yBounds, xBounds, steps):
    '''approximates
    integrate(f, (y, cFunc, dFunc), (x, a, b)),
    where
    * func must be a 2-variable function,
    * (cFunc, dFunc) = yBounds,
    * (a, b) = xBounds,
    * (j, i) = steps.
    '''
    j, i = steps
    a, b = xBounds
    cFunc, dFunc = [wrap_1_var_func(f_i) for f_i in yBounds]
    dx = float(b - a) / i
    I = 0
    for _i in range(i):
        for _j in range(j):
            x_i = a + dx*_i
            c_i = cFunc(x_i)
            d_i = dFunc(x_i)
            dy_i = float(d_i - c_i) / j
            y_j = c_i + dy_i*_j
            I += func(x_i, y_j)*dx*dy_i
    return I

def quad(func, xBounds, step):
    func2Var = lambda x, y: func(x)
    return quad2(func2Var, (0, 1), xBounds, (1, step))

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.