Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download

All published worksheets from http://sagenb.org

Views: 168742
Image: ubuntu2004

This is a modified (higher degree) version Harald's example.  We solve a pair of equations in a pair of unknowns:

var('y x') sol = solve([x + y^2 == 6, x^2 - y == 4], x, y) sol
[[x=2.42698224852,y=1.8902427767],[x=1.35852568876,y=2.15440792906],[x=1.15142718916,y=2.67421513124],[x=2.63408071749,y=2.93838061244]]\begin{array}{l}[\left[x = 2.42698224852, y = 1.8902427767\right],\\ \left[x = 1.35852568876, y = -2.15440792906\right],\\ \left[x = -1.15142718916, y = -2.67421513124\right],\\ \left[x = -2.63408071749, y = 2.93838061244\right]]\end{array}

We wish to apply a function f of two variables to each of these solutions:

f = 2*x + y f
y + {2 x}

Here's one approach, using Python's built-in map() function and a lambda, or "anonymous," function.  We note that this depends on the two values being in a specific order (first x, then y) for all solutions in sol:

map(lambda s: f(s[0].rhs(), s[1].rhs()), sol)
\left[6.74420727374, 0.562643448457, -4.97706950957, -2.32978082254\right]

However, we do not need to know the number of variables in advance.  Let's use Python's * operator, which converts a list into an argument list, and nested list comprehensions (why not?), to define another higher-order function:

def apply_func_to_sols(func, sols): return map(lambda x: func(*x), [[s.rhs() for s in t] for t in sols])

Again, we obtain the value of f "on" each of the solutions in sol:

apply_func_to_sols(f, sol)
\left[6.74420727374, 0.562643448457, -4.97706950957, -2.32978082254\right]

Finally, we simplify the recipe to get the same result:

def rhs(eq): return eq.rhs() [f(*map(rhs, s)) for s in sol]
\left[6.74420727374, 0.562643448457, -4.97706950957, -2.32978082254\right]

That was spectacular.