简体   繁体   English

julia中的循环速度和幂运算

[英]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? 如果1:10^25创建了该长度的序列/范围,并且for循环遍历那么多元素,怎么会这么快? also, 10^26 gives -2537764290115403776 while 10^28 is positive ( 4477988020393345024 ) and 10^80 is 0 . 同样, 10^26给出-253776429011540377610^28为正( 4477988020393345024 )和10^800 shouldn't these trigger some overflow error? 这些不应该触发一些溢出错误吗?

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). 其次,Julia使用64位未经检查的算法(假设使用64位计算机)来提高速度(与C,Java等相同)。

https://github.com/JeffreySarnoff/SaferIntegers.jl implements integers with overflow checks if you desire that behavior. 如果您希望这样做,则https://github.com/JeffreySarnoff/SaferIntegers.jl使用溢出检查实现整数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM