F. User
F. User

Reputation: 73

Changing variable in loop [Julia]

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)
end

However, I am getting errors that t1 and t0 are undefined. If I put a "global" in front of them, it works again. Is there a better way to handle this than by putting global variables all over my code?

Upvotes: 5

Views: 3755

Answers (1)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69819

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.

Upvotes: 3

Related Questions