【问题标题】:How can I mange the index of the loop in julia?如何管理 Julia 中的循环索引?
【发布时间】:2019-09-23 06:40:13
【问题描述】:

这是在 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

【问题讨论】:

    标签: julia julia-jump julia-studio


    【解决方案1】:

    问题是/ 运算符为整数参数提供浮点结果,而浮点结果不能用于索引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,或者位移运算符nc &gt;&gt; 2nc &gt;&gt;&gt; 2(对于欧几里得除以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 替换为我上面列出的选项之一。

    【讨论】:

      【解决方案2】:

      Julia 中的分数始终输出Float64,即使答案可以完全转换为Int

      重要的是,在您的情况下,请注意 Int 可用于索引数组,但 Float64 不能。所以你需要调整:

      for k=1:nc/2
      

      for k=1:Int(nc/2)
      

      这样您的索引k 将是Int 类型,而不是Float64

      如果不能保证nc 是偶数,那么您可能需要使用floor(Int, nc/2)ceil(Int, nc/2),具体取决于哪个更合适。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多