It is the section of the Genetic algorithm that is coding in Julia. the code was wrote as follow:
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
but it has this error. would you pleas help me?. why is it happened?
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
The problem is
/operator gives floating-point results for integer arguments and floating point results cannot be used for indexing anArray. You can index anArraywith anInteger.1:nc/4will create aFloat64range andk, aFloat64, is later used in indexing in your code atappend!(popc[k,1].position, m[1]);. You should, therefore, makekanInteger.If
ncis an integer, you should use Euclidean division withdiv(nc, 4)or simplync ÷ 4, or bit shift operatorsnc >> 2andnc >>> 2(for Euclidean division by 2^n you should shift by n). They will all give integer results for integer arguments.If
ncitself is a floating-point number, you should probably use one of the options pointed out by @Colin T Bowers.You do not have an error on the first line, since you do not use
ifor indexing here. It is still better to replacenc/4with one of the options I listed above.