在R中使用优化函数(优化)和dbinom(优化问题)

时间:2016-10-26 18:11:10

标签: r optimization

当p = 0.5时,n = 5且x = 3

dbinom(3,5,0.5) = 0.3125

让我们说我不知道​​p(n和x是已知的)并且想要找到它。

binp <- function(bp) dbinom(3,5,bp) - 0.3125
optimise(binp, c(0,1))

它不会返回0.5。另外,为什么

dbinom(3,5,0.5) == 0.3125 #FALSE

但是,

x <- dbinom(3,5,0.5)
x == dbinom(3,5,0.5) #TRUE

1 个答案:

答案 0 :(得分:2)

optimize()搜索最小化函数输出的参数。您的函数可以返回负值(例如,binp(0.1)-0.3044)。如果您搜索最小化与零差异的参数,则最好使用sqrt((...)^2)。如果你想让输出为零的参数,uniroot会帮助你。而你想要的参数并不是唯一决定的。 (注意; x <- dbinom(3, 5, 0.5); x == dbinom(3, 5, 0.5)dbinom(3, 5, 0.5) == dbinom(3, 5, 0.5)

相等
 ## check output of dbinom(3, 5, prob)
input <- seq(0, 1, 0.001)
output <- Vectorize(dbinom, "prob")(3, 5, input)
plot(input, output, type="l")
abline(h = dbinom(3, 5, 0.5), col = 2)     # there are two answers

enter image description here

max <- optimize(function(x) dbinom(3, 5, x), c(0, 1), maximum = T)$maximum  # [1] 0.6000006

binp <- function(bp) dbinom(3,5,bp) - 0.3125   # your function

uniroot(binp, c(0, max))$root # [1] 0.5000036
uniroot(binp, c(max, 1))$root # [1] 0.6946854


binp2 <- function(bp) sqrt((dbinom(3,5,bp) - 0.3125)^2)

optimize(binp2, c(0, max))$minimum  # [1] 0.499986
optimize(binp2, c(max, 1))$minimum  # [1] 0.6947186


dbinom(3, 5, 0.5) == 0.3125            # [1] FALSE
round(dbinom(3, 5, 0.5), 4) == 0.3125  # [1] TRUE
format(dbinom(3, 5, 0.5), digits = 16) # [1] "0.3124999999999999"