Changing variable in loop [Julia]

后端 未结 1 1035
死守一世寂寞
死守一世寂寞 2021-01-13 13:48

In Julia 1.0, I\'m trying to implement a for loop along the lines of:

while t1 < 2*tmax
    tcol = rand()
    t1 = t0 + tcol

    t0 = t1
    println(t0)
         


        
相关标签:
1条回答
  • 2021-01-13 14:25

    The reason of the problem is that you are running your code in global scope (probably in Julia REPL). In this case you will have to use global as is explained here https://docs.julialang.org/en/latest/manual/variables-and-scoping/.

    The simplest thing I can recommend is to wrap your code in let block like this:

    let t1=0.0, t0=0.0, tmax=2.0
        while t1 < 2*tmax
            tcol = rand()
            t1 = t0 + tcol
    
            t0 = t1
            println(t0)
        end
        t0, t1
    end
    

    This way let creates a local scope and if you run this block in global scope (e.g. in Julia REPL) all works OK. Note that I put t0, t1 at the end to make the let block return a tuple containing values of t0 and t1

    You could also wrap your code inside a function:

    function myfun(t1, t0, tmax)
        while t1 < 2*tmax
            tcol = rand()
            t1 = t0 + tcol
    
            t0 = t1
            println(t0)
        end
        t0, t1
    end
    

    and then call myfun with appropriate parameters to get the same result.

    0 讨论(0)
提交回复
热议问题