我想在 R 中做一些优化 - 问题是结果应该是整数(1, 2 ...)而不是浮点数(41.7313418341801 41.0267840987071 ...等等)。是否可以编辑代码以找到总值?
代码:
library(genalg)
evaluate <- function(X=c()) {
a <- c(3400, 2400, 2400, 1400, 1200, 3400, 1300, 2500)
b <- c(5600, 4600, 5100, 2400, 2200, 3400, 1300, 2500)
returnVal = NA;
d <- sum(ifelse(X >= 4, a, b) * X)
if (d<150000) {
returnVal = sum(c(-200000,-130000,-145000,-75000, -55000, -210000, -150000, -20000)\*X);
} else {
returnVal = 10000000000000
}
round(returnVal)
}
rbga.results <- rbga(c(0,0,0,0,0,0,0,0), c(44,63,63,107,125,44,115,60),
popSize = 3000, evalFunc = evaluate, iters = 15,
verbose = TRUE, mutationChance = 0.01)
summary(rbga.results,echo=TRUE)
我明白了: 大会结果 最佳解决方案:41.7313418341801 41.0267840987071 44.4433741739485 31.3764953238424 69.9314918310847 21.4769318029284 11.3982368202414 0.266784215345979
但我希望收到的结果是: 41 41 44 ....等等(没有结果与假设不符的风险 - 成本应低于 150000)。
第
X
轮和人口结果:
library(genalg)
set.seed(1073902509L)
evaluate <- function(X=c()) {
X <- round(X)
a <- c(3400, 2400, 2400, 1400, 1200, 3400, 1300, 2500)
b <- c(5600, 4600, 5100, 2400, 2200, 3400, 1300, 2500)
d <- sum(ifelse(X >= 4, a, b) * X)
if (d<150000) {
sum(c(-200000,-130000,-145000,-75000, -55000, -210000, -150000, -20000)*X)
} else {
d*1e6
}
}
system.time(
rbga.results <- rbga(c(0,0,0,0,0,0,0,0), c(44,63,63,107,125,44,115,60),
popSize = 3000, evalFunc = evaluate, iters = 15,
verbose = FALSE, mutationChance = 0.01)
)
#> user system elapsed
#> 10.89 0.69 11.60
rbga.results$population <- round(rbga.results$population)
summary(rbga.results,echo=TRUE)
#> GA Settings
#> Type = floats chromosome
#> Population size = 3000
#> Number of Generations = 15
#> Elitism = 600
#> Mutation Chance = 0.01
#>
#> Search Domain
#> Var 1 = [0,44]
#> Var 2 = [0,63]
#> Var 3 = [0,63]
#> Var 4 = [0,107]
#> Var 5 = [0,125]
#> Var 6 = [0,44]
#> Var 7 = [0,115]
#> Var 8 = [0,60]
#>
#> GA Results
#> Best Solution : 4 5 5 13 0 4 59 0
rbga.results$population[which.min(rbga.results$evaluations),]
#> [1] 4 5 5 13 0 4 59 0
rbga.results$best
#> [1] -7355000 -7355000 -7355000 -9565000 -9565000 -11245000 -11245000
#> [8] -11630000 -11630000 -11630000 -11630000 -12130000 -12130000 -12130000
#> [15] -12840000
evaluate(rbga.results$population[which.min(rbga.results$evaluations),])
#> [1] -12840000