For loop error?

Hi there,

I found something very weird:

 @time a=[x^2 for x in 1:1000000]
  0.022304 seconds (55.15 k allocations: 5.867 MiB)
1000000-element Array{Int32,1}:
          1
          4
          9
         16
         25
         36
         49
         64
         81
        100
        121
        144
        169
          ⋮
 -749379847
 -747379868
 -745379887
 -743379904
 -741379919
 -739379932
 -737379943
 -735379952
 -733379959
 -731379964
 -729379967
 -727379968

and if I change a little bit the code I obtain something else:

 @time a=[x^2 for x in 1:1e6]
  0.133631 seconds (422.38 k allocations: 23.197 MiB, 4.94% gc time)
1000000-element Array{Float64,1}:
   1.0
   4.0
   9.0
  16.0
  25.0
  36.0
  49.0
  64.0
  81.0
 100.0
 121.0
 144.0
 169.0
   ⋮
   9.99978000121e11
   9.999800001e11
   9.99982000081e11
   9.99984000064e11
   9.99986000049e11
   9.99988000036e11
   9.99990000025e11
   9.99992000016e11
   9.99994000009e11
   9.99996000004e11
   9.99998000001e11
   1.0e12

Why ? 1000000 is not equal with 1e6 ?

Thank you in advance!

I don’t have a 32-bit Julia at hand but scaling this up for 64 bits, maybe this gives an indication of what’s going on.

julia> typeof(10000000000000)
Int64

julia> typeof(1e13)
Float64

julia> 10000000000000^2   # Integer overflow
-2537764290115403776

julia> 1e13^2  # Floating point computation
1.0e26
1 Like

https://docs.julialang.org/en/v1/manual/faq/#Why-does-Julia-use-native-machine-integer-arithmetic?-1

Ok, thank you, I understand now!