在约束条件下优化R中的功能 [英] Optimize function in R with constraints
问题描述
我有这个功能
hazwil2 <- function(diam, flow, leng){
psi2=((1/(2.31*100))*1050*((flow/140)^1.852)*leng*diam^-4.87)
return(psi2)
}
我正在尝试使用optimize()
通过更改直径的值来最小化psi2
.
我不是在寻找绝对最小值,而是在将psi2
保持在2以下的最小直径.另外,我应该提到diam
是管道的直径,因此它只能是离散值, 2、3、4、5或6.
I'm trying to use optimize()
to minimize psi2
by varying the value of diam.
I'm not looking for an absolute minimum but for the smallest value of diam that will keep psi2
below 2. Also, I should mention that diam
is the diameter of a pipe, so it can only be a discrete values, 2, 3, 4, 5, or 6.
当我使用时:
optimize(
f = hazwil2,
interval = c(0.1,12),
flow = 100,
leng = 400
)
我得到了diam
的最大可能值(11.9),而psi2
的值很小.我的函数是单调的,因此最小化psi2
总是会导致最大的diam
.我想我正在为我的optimize()
函数设置约束.
I get the largest possible value of diam
(11.9), and a very small value for psi2
. My function is monotonic so the minimization of psi2
will always result in the largest possible diam
. I guess I'm struggling to set the constraints for my optimize()
function.
推荐答案
uniroot()
查找曲线/函数过零的位置.从PSI中减去2以找到最小允许直径.交叉点为3.564,因此4是将psi保持在2以下的最小整数.
uniroot()
finds the location where a curve/function crosses zero. Subtract 2 from the PSI to find the minimum allowable diameter. It crosses at 3.564, so 4 is the smallest integer that keeps psi under 2.
intercept <- 2L
uniroot(
function(x) hazwil2(x, 100, 400) - intercept ,
interval = c(3, 4)
)
curve(expr=hazwil2(x, 100, 400), from=2.5, to=5)
abline(a=intercept, b=0, col="blue")
curve()
图影响了3到4之间搜索直径的任意决定.
The curve()
graph influenced the arbitrary decision to search diameters between 3 and 4.
Result of `uniroot()`:
$`root`
[1] 3.564091
$f.root
[1] -5.618425e-05
$iter
[1] 6
$init.it
[1] NA
$estim.prec
[1] 6.103516e-05
这篇关于在约束条件下优化R中的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!