Search code examples
rlinear-programmingsolver

Solutions to a system of inequalities in R


Suppose I have the following system of inequalities:

  -2x + y <= -3
1.25x + y <= 2.5
        y >= -3

I want to find multiple tuples of (x, y) that satisfy the above inequalities.

library(Rglpk)

obj <- numeric(2)
mat <- matrix(c(-2, 1, 1.25, 1, 0, 1), nrow = 3)
dir <- c("<=", "<=", ">=")
rhs <- c(-3, 2.5, -3)

Rglpk_solve_LP(obj = obj, mat = mat, dir = dir, rhs = rhs)

Using the above code only seems to return 1 possible solution tuple (1.5, 0). Is possible to return other solution tuples?

Edit: Based on the comments, I would be interested to learn if there are any functions that could help me find the corner points.


Solution

  • Actually to understand the possible answers for the given question we can try to solve the system of inequalities graphically.

    There was a nice answer concerning plotting of inequations in R at stackowerflow. Using the given aproach we can plot the following graph:

    library(ggplot2)
    
    fun1 <- function(x) 2*x - 3        # this is the same as -2x + y <= -3
    fun2 <- function(x) -1.25*x + 2.5  # 1.25x + y <= 2.5
    fun3 <- function(x) -3             # y >= -3
    x1 = seq(-1,5, by = 1/16)
    mydf = data.frame(x1, y1=fun1(x1), y2=fun2(x1),y3= fun3(x1))
    mydf <-  transform(mydf, z = pmax(y3,pmin(y1,y2)))
    ggplot(mydf, aes(x = x1)) + 
      geom_line(aes(y = y1), colour = 'blue') +
      geom_line(aes(y = y2), colour = 'green') +
      geom_line(aes(y = y3), colour = 'red') +
      geom_ribbon(aes(ymin=y3,ymax = z), fill = 'gray60')
    

    enter image description here

    All the possible (infinite by number) tuples lie inside the gray triangle. The vertexes can be found using the following code.

    obj <- numeric(2)
    mat <- matrix(c(-2, 1.25, 1, 1), nrow = 2)
    rhs <- matrix(c(-3, 2.5), nrow = 2)
    
    aPoint <- solve(mat, rhs)
    
    mat <- matrix(c(-2, 0, 1, 1), nrow = 2)
    rhs <- matrix(c(-3, -3), nrow = 2)
    
    bPoint <- solve(mat, rhs)
    
    mat <- matrix(c(1.25, 0, 1, 1), nrow = 2)
    rhs <- matrix(c(2.5, -3), nrow = 2)
    
    cPoint <- solve(mat, rhs) 
    

    Note the order of arguments of matrices.

    And you get the coordinates:

    > aPoint
              [,1]
    [1,] 1.6923077
    [2,] 0.3846154
    > bPoint
         [,1]
    [1,]    0
    [2,]   -3
    > cPoint
         [,1]
    [1,]  4.4
    [2,] -3.0