user11803410
user11803410

Reputation: 35

for loop speed and exponentiation in julia

i timed the following code in julia:

function foo()
  for x=1:10^25
      y = 1 + 2
  end
end

the result seems unrealistic:

@time foo()
  0.017498 seconds (46.44 k allocations: 2.640 MiB)

if 1:10^25 creates a sequence/range of that length and the for loop iterates through that many elements how could it be so fast? also, 10^26 gives -2537764290115403776 while 10^28 is positive (4477988020393345024) and 10^80 is 0. shouldn't these trigger some overflow error?

Upvotes: 0

Views: 154

Answers (1)

Oscar Smith
Oscar Smith

Reputation: 6398

There are a few things happening here. Firstly, ranges are lazy, so it never constructs. Second of all, Julia uses 64 bit unchecked arithmetic (assuming 64 bit computer) for speed (same as C, Java, etc).

https://github.com/JeffreySarnoff/SaferIntegers.jl implements integers with overflow checks if you desire that behavior.

Upvotes: 1

Related Questions