【发布时间】:2023-03-12 07:05:02
【问题描述】:
我对 R 比较陌生,需要建立一个遗传算法来找到一个能产生一定数量素数的方程。
install.packages("GA")
install.packages("matlab")
library(GA)
library(matlab)
f <- function(x)
{
#initialize fitness score
score <- 0
#set test values for k
k <- seq(from = 1, to = 100,by = 1)
#test if the result of the formula (k^2 + ak + b) is a prime number using test k values
for (i in k) {
if (isprime(i ^ 2 + x[1] * i + x[2]) == 2) {
score = score + 1
}
}
#return fitness score
return(score)
}
lbound <- 2
ubound <- 1000
GA <- ga(type="real-valued",fitness=f,popSize = 10,pcrossover = 0.8,pmutation = 0.1, maxiter=30, run=20, lower = lbound, upper = ubound)
当我尝试运行 GA 部分时,我收到以下错误:
> GA <- ga(type="real-valued",fitness=f,popSize = 10,pcrossover = 0.8,pmutation = 0.1, maxiter=30, run=20, lower = lbound, upper = ubound)
Error in if (any(x < 0)) { : missing value where TRUE/FALSE needed
对我可能做错的任何建议?
谢谢
【问题讨论】:
标签: r genetic-algorithm