Coroutines¶
Consider the following skeleton for a root-finding code based on the secant method:
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)
Suppose one wants to implement this in the following way:
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: