while-loopjulia

Julia code does not break out of the loop


I have written the following code in Julia to output an array of Fibonacci numbers less than or equal to 4000000:

F = []
fib_1 = 0
fib_2 = 1

push!(F, fib_1, fib_2)

while fib_2 <= 4000000
  next_fib = fib_2 + fib_1
  push!(F, next_fib)
  fib_1 = fib_2
  fib_2 = next_fib
end
println(F)

For some reason, a number greater than 4000000 also gets pushed into the array as shown in bold below:

Any[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887]

There seems to be something wrong with my while condition but for the world of me cannot see what.

I am from a Python background and am new to Julia so any help to demystify this is greatly appreciated.

Many thanks.


Solution

  • After a new value is calculated next_fib = fib_2 + fib_1, it is immediately pushed into the array, without being checked. The check fib_2 <= 4000000 instead needs to happen between the calculation and the push!. (The equivalent Python code returns the exact same result, by the way, so this is independent of language semantics.)

    You can change the code instead to something like:

    function fibo(limit = 4000000)
      fib_1 = 0
      fib_2 = 1
      F = [fib_1]
    
      while fib_2 <= limit
        push!(F, fib_2)
        fib_1, fib_2 = fib_2, fib_1 + fib_2
      end
    
      return F
    end
    
    println(fibo())
    

    (Writing things in functions and avoiding global scope is a pretty important habit to get into if you wish to take advantage Julia's performance benefits. Also, initializing F = [fib_1] instead of F = [] creates it as an array of Int64 instead of the slower Any array - in general, var = [] lines in Julia code should ring some alarm bells, and should be changed to in some way specify the type of the array's elements.)