Some problems come up when I use the function lsqlincon()
of the package pracma
in R. I want to solve a quadratic optimization with linear equality and inequality constraints. For example, the least square solution with the constraint that every entry of the solution must be larger or equal to zero and the sum of all entries of the solution must be one. I use the following code:
library(MASS)
set.seed(1)
X <- mvrnorm(n = 100, mu = rep(0, 10), Sigma = diag(1, 10))
y <- rnorm(100)
library(pracma)
C <- X
d <- y
Aeq <- matrix(rep(1, ncol(C)), 1)
beq <- 1
lb <- rep(0, ncol(C))
(weight <- lsqlincon(C = C, d = d, Aeq = Aeq, beq = beq, lb = lb))
[1] 1.711997e-01 -7.383626e-21 1.707092e-01 1.361470e-01 1.475174e-01
[6] 8.595312e-02 1.217463e-01 1.391139e-01 2.761332e-02 0.000000e+00
But the second entry of the weight return is -7.383626e-21, and it's a negative number. If I try to use lb <- rep(1e-18, ncol(C))
, the problem above still exists:
lb <- rep(1e-18, ncol(C))
(weight <- lsqlincon(C = C, d = d, Aeq = Aeq, beq = beq, lb = lb))
[1] 1.711997e-01 -7.383626e-21 1.707092e-01 1.361470e-01 1.475174e-01
[6] 8.595312e-02 1.217463e-01 1.391139e-01 2.761332e-02 0.000000e+00
It's really strange and I don't know why. How could I fix this? Treat -7.383626e-21 as 0?