Solving a system of equations with Python and Pulp

Solve a linear problem with Python and Pulp

Pulp is a python library to solve linear problems. Linear problem can be written mathematically like

This is a complex example. In this article, you can learn Pulp with a very simple example.

Installation of Pulp

The easiest way to install pulp is via PyPi.

If pip is available on your computer,

pip install pulp

If you want to install latest version of pulp from GitHub, use this.

pip install -U git+https://github.com/coin-or/pulp

Linear system of equations

The system of equations that we are going to solve is

The answers are x = 2 and y = 3.

First, we are going to define the variables x and y. We use LpVariable() to define a variable for linear problem. “x” and “y” are the names of the variables. In order to see the value, use like x.value()

from pulp import *
# LP Variables
x = LpVariable("x", 0, 5)   # variable x with 0 <= x <= 5
y = LpVariable("y", 0, 5)   # variable x with 0 <= y <= 5

Next, we are going to define a “Linear Problem.” The problem is treated as minimization problem.

prob = LpProblem("myProblem", LpMinimize)

Now we are going to put some constraints to the problem.

# Constraints
prob += x + y == 5
prob += 2*x - y == 1

Finally, to solve the problem,

# Solve
status = prob.solve(PULP_CBC_CMD(msg=0))

Then, we can see the results as follows

# -3: not defined  -2: infinite solution -1: cannot be executed 0: no solution 1: optimized solution
if status == 1:
    # result
    print("x =", x.value(), "y =", y.value())
> x = 2.0 y = 3.0

“status” shows if the optimization problem was successfully solved.

Full code

from pulp import *

# LP Variables
x = LpVariable("x", 0, 5)   # variable x with 0 <= x <= 5
y = LpVariable("y", 0, 5)   # variable x with 0 <= y <= 5

# Use LpProblem() to create new problems. Create “myProblem”:
prob = LpProblem("myProblem", LpMinimize)

# Constraints
prob += x + y == 5
prob += 2*x - y == 1

# Solve
status = prob.solve(PULP_CBC_CMD(msg=0))

# -3: not defined  -2: infinite solution -1: cannot be executed 0: no solution 1: optimized solution
if status == 1:
    # result
    print("x =", x.value(), "y =", y.value())

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s