在循环中更改变量 [Julia] [英] Changing variable in loop [Julia]

查看:20
本文介绍了在循环中更改变量 [Julia]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Julia 1.0 中,我尝试按照以下方式实现 for 循环:

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

但是,我收到 t1 和 t0 未定义的错误.如果我在他们面前放一个全球",它会再次起作用.有没有比在我的代码中放置全局变量更好的方法来处理这个问题?

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?

推荐答案

问题的原因是您在全局范围内运行代码(可能在 Julia REPL 中).在这种情况下,您将必须使用 global ,如此处所述 https://docs.julialang.org/en/latest/manual/variables-and-scoping/.

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/.

我可以推荐的最简单的方法是将代码包装在 let 块中,如下所示:

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

这种方式 let 创建一个本地范围,如果你在全局范围内运行这个块(例如在 Julia REPL 中)一切正常.请注意,我将 t0, t1 放在末尾以使 let 块返回一个包含 t0t1

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

然后用适当的参数调用myfun得到同样的结果.

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

这篇关于在循环中更改变量 [Julia]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆