rsolnp等式约束未满足咨询:为何我的等式约束不生效?
Why Rsolnp Isn't Satisfying Your Equality Constraint
Ah, I spot the issue here—you're missing a critical parameter when calling solnp() that tells the solver what value your equality constraint should equal.
Let's break this down clearly:
- The
solnpfunction requires both an equality constraint function (eqfun) and the target value that function must equal (eqB). - Your
g()function returnssum(p)-1, which means you wantsum(p)-1 = 0(i.e.,sum(p) = 1). But in your code, you only passedgas the third argument (which maps toeqfun), but never specifiedeqB = 0. Without that target value, the solver doesn't know to enforce the constraint at all!
Fixed Code
Here's how to adjust your code to properly enforce the sum(p) = 1 constraint:
require(Rsolnp) # Target function (note: this is negative entropy; if you want to maximize entropy, see the side note below) f <- function(p) { sum(p*log(p)) } # Option 1: Constraint function returns sum(p)-1, target is 0 g1 <- function(p) { sum(p) - 1 } p0 <- runif(10) p0 <- p0/sum(p0) # Initial value already satisfies the constraint res1 <- solnp(p0, f, eqfun = g1, eqB = 0) print(g1(res1$par)) # Should be very close to 0 (due to numerical precision) # Option 2: More intuitive constraint function, target is 1 g2 <- function(p) { sum(p) } res2 <- solnp(p0, f, eqfun = g2, eqB = 1) print(g2(res2$par)) # Should be very close to 1
Quick Side Note
If your goal is to maximize entropy (a common use case for this constraint), remember that sum(p*log(p)) is the negative of entropy. You can either:
- Modify the target function to
-sum(p*log(p)), or - Add
control = list(maximize = TRUE)to yoursolnpcall:res <- solnp(p0, f, eqfun = g2, eqB = 1, control = list(maximize = TRUE))
内容的提问来源于stack exchange,提问作者Michael Moos
相关产品推荐
相关产品推荐

