On Thu, Nov 17, 2011 at 3:16 PM, Joon Lee <jundo...@gmail.com> wrote:
> I'm trying to solve the 'barnyard' problem with sympy with two
> equations for 3 variables (it's underconstrained).  I want all
> possible solutions to be displayed, possibly by iterating
>
> There are 20 heads and 56 legs, how many chicken, pigs and spiders are
> there?
>
> chickens = Symbol('chickens')
> pigs = Symbol('pigs')
> spiders = Symbol('spiders')
>
> solve([Eq(chickens+pigs+spiders, 20), Eq(2*chickens+4*pigs+8*spiders,
> 56)])
>
> this works, but defines chickens and pigs in terms of spiders.

That's because you have two equations and three unknowns, so one of
the unknowns will be free (any number for spiders satisfying the
equations it gives you for chickens and pigs will satisfy the
equations).

If you want spiders to be an integer, you can try substituting integer
values.  The following one liner tries from 0 to 10 spiders:

In [19]: [{spiders:i, chickens:soln[chickens].subs(spiders, i),
pigs:soln[pigs].subs(spiders, i)} for i in range(10)]
Out[19]:
[{chickens: 12, pigs: 8, spiders: 0}, {chickens: 14, pigs: 5, spiders:
1}, {chickens: 16, pigs: 2, spiders: 2}, {chickens: 18, pigs: -1,
spiders: 3}, {chickens: 20, pigs: -4, spiders: 4}, {chickens: 22,
 pigs: -7, spiders: 5}, {chickens: 24, pigs: -10, spiders: 6},
{chickens: 26, pigs: -13, spiders: 7}, {chickens: 28, pigs: -16,
spiders: 8}, {chickens: 30, pigs: -19, spiders: 9}]

You can see that only 0, 1, or 2 spiders makes sense, or else you have
a negative number of animals.  So the possible solutions are:

In [21]: [{spiders:i, chickens:soln[chickens].subs(spiders, i),
pigs:soln[pigs].subs(spiders, i)} for i in range(3)]
Out[21]: [{chickens: 12, pigs: 8, spiders: 0}, {chickens: 14, pigs: 5,
spiders: 1}, {chickens: 16, pigs: 2, spiders: 2}]

> I'm trying to have sympy display all the possible solutions by adding
> a few more expressions to the solver:
> soln = solve([Eq(chickens+y+z, 20), Eq(2*chickens + 4*y + 8*z, 56),
> Ge(chickens,0), Ge(y,0), Ge(z,0)])
>
> , but I'm getting an error:
> NotImplementedError: only univariate inequalities are supported
>
> Am I doing something wrong?
>

No, you are not doing anything wrong. NotImplementedError means just
what it says: that it is not implemented.  In this case, it cannot
solve systems of inequalities.  Unfortunately, our inequalities solver
is still in its infant stages, so SymPy cannot yet do this directly.
But as you saw above, you can use additional knowledge, i.e., the fact
that the variables have to be nonnegative integers, to easily iterate
all possible solutions.

Aaron Meurer

-- 
You received this message because you are subscribed to the Google Groups 
"sympy" group.
To post to this group, send email to sympy@googlegroups.com.
To unsubscribe from this group, send email to 
sympy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sympy?hl=en.

Reply via email to