You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 solnp function requires both an equality constraint function (eqfun) and the target value that function must equal (eqB).
  • Your g() function returns sum(p)-1, which means you want sum(p)-1 = 0 (i.e., sum(p) = 1). But in your code, you only passed g as the third argument (which maps to eqfun), but never specified eqB = 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 your solnp call:
    res <- solnp(p0, f, eqfun = g2, eqB = 1, control = list(maximize = TRUE))
    

内容的提问来源于stack exchange,提问作者Michael Moos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:24:46