是朱莉娅(Julia(编码的遗传算法的部分。该代码的编写如下:
popc= [individual(rand(0:1,nvar),[]) for i in 1:nc/4,j in 1:2];
for k=1:nc/4
#select firdt parent
i1=rand(1:npop);
p1=pop[i1];
#select second parent
i2=rand(1:npop);
if i1==i2
i2=rand(1:npop);
end
p2=pop[i2]
#apply crossover
m=singlepointcrossover(p1.position,p2.position);
append!(popc[k,1].position, m[1]);
append!(popc[k,2].position, m[2]);
end
function singlepointcrossover(x1,x2)
nvar=length(x1);
cutpoint=rand(1:nvar-1);
y1=append!(x1[1:cutpoint],x2[cutpoint+1:end]);
y2=append!(x2[1:cutpoint],x1[cutpoint+1:end]);
return y1,y2
end
但是它有此错误。你会请帮我吗?为什么发生?
ArgumentError: invalid index: 1.0
getindex(::Array{individual,2}, ::Float64, ::Int64) at abstractarray.jl:883
macro expansion at GA.juliarc.jl:87 [inlined]
anonymous at <missing>:?
include_string(::String, ::String) at loading.jl:522
include_string(::String, ::String, ::Int64) at eval.jl:30
include_string(::Module, ::String, ::String, ::Int64, ::Vararg{Int64,N} where N) at eval.jl:34
(::Atom.##102#107{String,Int64,String})() at eval.jl:82
withpath(::Atom.##102#107{String,Int64,String}, ::String) at utils.jl:30
withpath(::Function, ::String) at eval.jl:38
hideprompt(::Atom.##101#106{String,Int64,String}) at repl.jl:67
macro expansion at eval.jl:80 [inlined]
(::Atom.##100#105{Dict{String,Any}})() at task.jl:80
问题是/
操作员为整数参数提供浮点结果,而浮点结果不能用于索引Array
。您可以用Integer
索引Array
。
/(x,y(
右除法运算符:
x
乘以y
的倒数 正确的。给出整数参数的浮点结果。
for k=1:nc/4
1:nc/4
将创建一个Float64
范围,而k
(Float64
(随后在append!(popc[k,1].position, m[1]);
的代码中索引中。因此,您应该使k
成为Integer
。
如果nc
是整数,则应使用div(nc, 4)
或nc ÷ 4
或BIT SHIFT OPERATOR nc >> 2
和nc >>> 2
使用Euclidean Division(对于Euclidean Disecon 2^n,您应该换一个n(。他们都将为整数参数提供整数结果。
如果nc
本身是浮点数,则可能应该使用@Colin t Bowers指出的选项之一。
popc= [individual(rand(0:1,nvar),[]) for i in 1:nc/4,j in 1:2];
您没有在第一行上没有错误,因为您不使用i
在此处索引。最好将nc/4
替换为我上面列出的选项之一。
朱莉娅(Julia(中的分数总是输出 Float64
,即使答案可以将答案完全转换为 Int
。
重要的是,在您的情况下,请注意Int
可以用于索引数组,但是Float64
不能。因此,您需要调整:
for k=1:nc/2
to
for k=1:Int(nc/2)
,您的索引k
将为Int
类型,而不是Float64
。
如果不能保证nc
是偶数整数,则您可能需要使用floor(Int, nc/2)
或ceil(Int, nc/2)
,具体取决于更合适的情况。