Wojciech Moszczyński
Wojciech Moszczyński

Reputation: 3177

How to find a solution with three unknowns in Python

How can I solve this in Python?

enter image description here

Something feels like it would be a loop or some kind of solver. I know I can solve it by trial and error, but that's not the point.

Upvotes: 2

Views: 794

Answers (2)

jb4earth
jb4earth

Reputation: 188

As mentioned by @dantechguy, there are infinite answers, but that doesn't mean we can't get python to tell us that for sure. Best route for systems of equations solving is sympy. Check it out here: Sympy

The following will solve your system of equations and tell you for each variable, and tell you the bounds of each.

from sympy.solvers import solve
from sympy import S

x1,x2,x3 = S('x1 x2 x3'.split())
Eq = [1*x1 + 3*x2 + 5*x3-1200, x1>0, x2>0,x3>0]
sol = solve(Eq, x1),solve(Eq, x2),solve(Eq, x3)
display(sol)

This outputs:

((0 < x1) & (0 < x2) & (0 < x3) & (x1 < oo) & (x2 < oo) & (x3 < oo) & Eq(x1, -3*x2 - 5*x3 + 1200),
 (0 < x1) & (0 < x2) & (0 < x3) & (x1 < oo) & (x2 < oo) & (x3 < oo) & Eq(x2, -x1/3 - 5*x3/3 + 400),
 (0 < x1) & (0 < x2) & (0 < x3) & (x1 < oo) & (x2 < oo) & (x3 < oo) & Eq(x3, -x1/5 - 3*x2/5 + 240))

If you're working in a jupyter, use the following to make things show up nicely typeset with LATEX:

display(solve(Eq, x1))
display(solve(Eq, x2))
display(solve(Eq, x3))

enter image description here

Upvotes: 0

dwb
dwb

Reputation: 2624

There are infinite solutions, so as long as you have two of the x values you can find the third required to reach 1200.

So say you have X1 and X2, some simple algebra tells us:

5*X3 = 1200 - X1 - 3*X2

and then

X3 = (1200 - X1 - 3*X2) / 5

so there you have found X3 with values for X1 and X2. To find a variety of solutions, you could fill X1 and X2 with random numbers and then get the third X3 to match.

Upvotes: 2

Related Questions