Problem variable declaration

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)

You are running quite an old Julia version 1.0 , 1.4?
You should update to the current release.

But what you see is the infamous rule of scope:
In general: Scope of Variables · The Julia Language

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 your suggestions, but I am running 1.7.0. SO did you mean to use function always?

I don’t get the error since version 1.5 and I tried 1.5, 1.6 and 1.7.0 and 1.7.1 now in a plain REPL and in 1.6.1 in a VSCode REPL.

Using functions is in general a recommended thing in Julia.

Do you have something about scope activated like e.g. GitHub - stevengj/SoftGlobalScope.jl: utilities for "soft" global scope in interactive Julia environments from your startup.jl files. This file is currently located in ~/.julia/config/ .

Perhaps the output of versioninfo() and ] st helps to understand why you get the error in 1.7.1 and I do not.

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.

Next is the startup.jl file. I am using MAC and in my .julia folder, there is no config file.

Extremely sorry to bother you, but I desperately need the solution. Please let me know if you need to know anything else.

Many thanks for your time.

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

let
...
end

around everything.

1 Like

Thanks a lot. It works.