I have written a simple code of gradient descent. It runs well in Jupyter, but when I try to execute it on VS Code or run from Julia REPL, it shows an error that
“LoadError: UndefVarError: x_old not defined”
The code is as below:
maxitr=100
itr=1
x_old=10
L=0.1
x_new=[ ]
while itr<maxitr
x_new=x_old-L*2(x_old-4)
if abs(x_new-x_old)>10^-10
x_old=x_new
itr=itr+1
end
end
print(x_new)
For your Julia 1.0 you can put all your code into a function to solve it:
julia> function myFunc()
maxitr=100
itr=1
x_old=10
L=0.1
x_new=[ ]
while itr<maxitr
x_new=x_old-L*2(x_old-4)
if abs(x_new-x_old)>10^-10
x_old=x_new
itr=itr+1
end
end
x_new
end
julia> print( myFunc() )
4.000000001527777
or you can use a let block:
let x_old=10, itr=1, x_new=[ ], maxitr=100, L=0.1
while itr<maxitr
x_new=x_old-L*2(x_old-4)
if abs(x_new-x_old)>10^-10
x_old=x_new
itr=itr+1
end
end
print(x_new)
end
There are other solutions like using global, but the best is to upgrade to the current release.
Thanks Oheil for the documents. I have gone through this. The global/local scope should not there in 1.7.1. Although I installed the package "SoftGlobalScope:, but still I have the same output. I have attached one screenshot of my terminal.
Ah, I see. I thought you are running your code in the REPL as you said in the OP.
FYI the REPL is the interactive command line which waits for your input when you start julia without a .jl file.
You can solve your issue the easiest by putting