Simple for loop woth if condition in Julia

I’m trying to implement the following:

res = 0.0 
res0= 0.0 

for i = 1:10
    
    res = 0.5^i
    
    if i==1 
       res0 = copy(res)
    end 
    
   res = copy(res)/res0
   println(res)
end

but when I run it I get the following error:

1.0
ERROR: LoadError: UndefVarError: res0 not defined
Stacktrace:
 [1] top-level scope at /home/rohit/Desktop/cfd_julia/sample.jl:12
 [2] include(::Module, ::String) at ./Base.jl:377
 [3] exec_options(::Base.JLOptions) at ./client.jl:288
 [4] _start() at ./client.jl:484
in expression starting at /home/rohit/Desktop/cfd_julia/sample.jl:4

Fortran Equivalent I’m attempting to recode in Julia:

program main
real(8) :: res,res0
integer :: i


res = 0.0 
res0= 0.0 

do i = 1,10
   res = 0.5d0**i
   if(i.eq.1) then
     res0 = res 
   endif
   res = res/res0
   print*, res 
enddo
endprogram

I seem to be misunderstanding how copy, value assignment and scope of variables work in Julia, what am I missing? Thanks in advance!

Put your code in a function or let block and it’ll work (it will also avoid being painfully slow) Scope of Variables · The Julia Language

Alternatively, you can upgrade to version 1.5, where your code will no longer error but will still be inefficient.

1 Like

Thanks for the advice I’ll look into the let block. So what was my problem, just the version? I mean did the scope of variables change over versions?

Scoping rules changed for the REPL. You can take a look at the julia manual page on scope, in particular this section:
https://docs.julialang.org/en/v1/manual/variables-and-scoping/#On-Soft-Scope
And the release notes:
https://docs.julialang.org/en/v1/NEWS/#Language-changes

3 Likes

res is a scalar of an immutable value type. It doesn’t make sense to copy them.

Remove all the copys, and put your code in a function.

1 Like

Not sure what you actually need to accomplish, but here are two alternatives; one that returns a vector of the values you are trying to calculate, and one that just prints the values one-by-one:

function foo(N)
    res = 2.0
    return [res *= 0.5 for i in 1:N]
end

function bar(N)
    res = 2.0
    for i in 1:N
        res *= 0.5
        println(res)
    end
end
julia> foo(10)
10-element Array{Float64,1}:
 1.0
 0.5
 0.25
 0.125
 0.0625
 0.03125
 0.015625
 0.0078125
 0.00390625
 0.001953125

julia> bar(10)
1.0
0.5
0.25
0.125
0.0625
0.03125
0.015625
0.0078125
0.00390625
0.001953125
1 Like