Department of Physics and Astronomy

The Forbes Group

coroutines

$\newcommand{\vect}[1]{\mathbf{#1}} \newcommand{\uvect}[1]{\hat{#1}} \newcommand{\abs}[1]{\lvert#1\rvert} \newcommand{\norm}[1]{\lVert#1\rVert} \newcommand{\I}{\mathrm{i}} \newcommand{\ket}[1]{\left|#1\right\rangle} \newcommand{\bra}[1]{\left\langle#1\right|} \newcommand{\braket}[1]{\langle#1\rangle} \newcommand{\op}[1]{\mathbf{#1}} \newcommand{\mat}[1]{\mathbf{#1}} \newcommand{\d}{\mathrm{d}} \newcommand{\pdiff}[3][]{\frac{\partial^{#1} #2}{\partial {#3}^{#1}}} \newcommand{\diff}[3][]{\frac{\d^{#1} #2}{\d {#3}^{#1}}} \newcommand{\ddiff}[3][]{\frac{\delta^{#1} #2}{\delta {#3}^{#1}}} \DeclareMathOperator{\erf}{erf} \DeclareMathOperator{\Tr}{Tr} \DeclareMathOperator{\order}{O} \DeclareMathOperator{\diag}{diag} \DeclareMathOperator{\sgn}{sgn} \DeclareMathOperator{\sech}{sech} $

Coroutines

Consider the following skeleton for a root-finding code based on the secant method:

In [9]:
def f(x):
    return x**2 - 2.0

def find_root(f, x0, dx=0.1, xtol=1e-16, ftol=1e-8):
    f0 = f(x0)
    x1 = x0 + dx
    while True:
        f1 = f(x1)
        if abs(x1-x0) < xtol or abs(f1) < ftol:
            break
        df = (f1 - f0)/(x1 - x0)
        x0, f0, x1 = x1, f1, x1 - f1/df

    return x1, f1

find_root(f, 0)
Out[9]:
(1.414213562373082, -3.68594044175552e-14)

Suppose one wants to implement this in the following way:

In [13]:
def sqrt(y, xtol=1e-16, ftol=1e-8):
    x = y
    while True:
        x0 = x
        f = x**2 - y
        x = next_x(x, f)
        if abs(x-x0) < xtol or abs(f) < ftol:
            break
    return  x, f

Physicists often seem to write code like this where their first version "embeds" the minimization algorithm. Coroutines allow us a way to preserve this type of code stucture which some people find intuitive.

How can we write the function next_x? Coroutines give use a solution.

Coroutines in C++

Apparently there are some libraries for writing coroutines in C++.

Boost has one which might not be portable:

Also, there is the following library: