I get variable not defined error in a trivial example

So at REPL I typed the following

julia> using Polynomials

julia> p=Poly([5,-3,-2,-2,1,1])
Poly(5 - 3*x - 2*x^2 - 2*x^3 + x^4 + x^5)

julia> dp=polyder(p)
Poly(-3 - 4*x - 6*x^2 + 4*x^3 + 5*x^4)

julia> function newtonIteration(p,dp,x)
           return x-p(x)/dp(x)
       end
newtonIteration (generic function with 1 method)

julia> x=2
2

julia> x = newtonIteration(p,dp,x)
1.7012987012987013

julia> for i in 1:10
           print(x)
           x = newtonIteration(p,dp,x)
       end
ERROR: UndefVarError: x not defined
Stacktrace:
 [1] top-level scope at .\REPL[7]:2

I really don’t understand what has gone wrong here. Does for live in a different namespace. What is happening?

By the way, I know that the Newton method has already been implemented, I am just interested at the bug I get in this case.

You can use global x inside the loop to declare that you are referring to the global variable x, otherwise the for loop introduces a new local variable x.

But a better solution all around is just to put your code into a function:

function solve()
  x = newtonIteration(x, ...)
  for i in 1:10 
    x = newtonIteration(x, ...)
  end
end
1 Like

Oh, I see. This is happening now. It is kind of a pain.

Thanks!