R 中的非线性离散优化

Pao*_*tto 5 optimization r constraints discrete-mathematics

我有一个简单的(实际上是经济学标准)非线性约束离散最大化问题需要在 R 中解决,但遇到了麻烦。我找到了部分问题的解决方案(非线性最大化;离散最大化),但没有找到所有问题的联合。

\n\n

问题就在这里。消费者想要购买三种产品(凤梨、香蕉、饼干),知道价格并且预算为 20\xe2\x82\xac。他喜欢多样化(即,如果可能的话,他希望拥有所有三种产品),并且他的满意度随着消费量的增加而降低(他更喜欢他的第一块饼干,而不是他的第 100 块)。

\n\n

他希望最大化的函数是

\n\n

函数最大化

\n\n

当然,由于每个人都有一个价格,而且他的预算有限,他在以下约束下最大化了这个功能:

\n\n

在此输入图像描述

\n\n

我想做的是找到满足约束条件的最优购买清单(N 条香蕉,M 条香蕉,K 条饼干)。

\n\n

如果问题是线性的,我会简单地使用 linprog::solveLP()。但目标函数是非线性的。\n如果问题具有连续性质,则将有一个简单的解析解。

\n\n

这个问题是离散和非线性的,我不知道如何进行。

\n\n

这里有一些可以玩的玩具数据。

\n\n
df <- data.frame(rbind(c("ananas",2.17),c("banana",0.75),c("cookie",1.34)))\nnames(df) <- c("product","price")\n
Run Code Online (Sandbox Code Playgroud)\n\n

我想要一个优化例程,为我提供 (N,M,K) 的最佳购买清单。

\n\n

有什么提示吗?

\n

G. *_*eck 2

1)没有包这可以通过暴力来完成。使用df问题作为输入,确保它price是数字(它是问题的一个因素df)并计算每个变量的最大数字mx。然后创建g变量计数网格并计算total每个变量的价格以及相关的objective捐赠gg。现在gg按目标降序排序,并取满足约束的解决方案。 head将显示前几个解决方案。

price <- as.numeric(as.character(df$price))
mx <- ceiling(20/price)
g <- expand.grid(ana = 0:mx[1], ban = 0:mx[2], cook = 0:mx[3]) 
gg <- transform(g, total = as.matrix(g) %*% price, objective = sqrt(ana * ban * cook))
best <- subset(gg[order(-gg$objective), ], total <= 20)
Run Code Online (Sandbox Code Playgroud)

给予:

> head(best) # 1st row is best soln, 2nd row is next best, etc.
     ana ban cook total objective
1643   3   9    5 19.96  11.61895
1929   3   7    6 19.80  11.22497
1346   3  10    4 19.37  10.95445
1611   4   6    5 19.88  10.95445
1632   3   8    5 19.21  10.95445
1961   2  10    6 19.88  10.95445
Run Code Online (Sandbox Code Playgroud)

2) dplyr这也可以使用 dplyr 包很好地表达。使用上面的gand price

library(dplyr)
g %>% 
  mutate(total = c(as.matrix(g) %*% price), objective = sqrt(ana * ban * cook)) %>%
  filter(total <= 20) %>%
  arrange(desc(objective)) %>%
  top_n(6)
Run Code Online (Sandbox Code Playgroud)

给予:

Selecting by objective
  ana ban cook total objective
1   3   9    5 19.96  11.61895
2   3   7    6 19.80  11.22497
3   3  10    4 19.37  10.95445
4   4   6    5 19.88  10.95445
5   3   8    5 19.21  10.95445
6   2  10    6 19.88  10.95445
Run Code Online (Sandbox Code Playgroud)