哪个更好用`Int((n + 1)/ 2)`,`round(Int,(n + 1)/ 2)`或`Int((n + 1)// 2)`?

Paa*_*lon 2 julia

我有一个奇数n,想(n+1)/2用作数组索引.计算指数的最佳方法是什么?我想出来使用Int((n+1)/2),round(Int, (n+1)/2))Int((n+1)//2).哪个更好或者不是我需要太担心它们?

hck*_*ckr 11

为了获得更好的性能,您需要整数除法(div÷)./给出整数参数的浮点结果.//给出一个Rational不是整数.所以你需要写div(n+1, 2)(n+1) ÷ 2.要打字÷你可以写\div,然后在julia REPL,Jupyter笔记本,Atom等上按TAB键.

即使被除数(n + 1)是偶数,你需要整数除法直接获得整数结果,否则你需要将结果转换为整数,与整数除法相比,这又是昂贵的.

您也可以使用右移位运算符 >>无符号右移位运算符 >>>,因为整数除法2^n对应于将该整数的位向右移位n次.尽管编译器将以2的幂的整数除法降低到位移操作,但如果被除数是有符号整数(即Int而不是UInt),则编译的代码仍将具有额外的步骤.因此,使用正确的位移运算符可能会提供更好的性能,尽管这可能是一个过早的优化并影响代码的可读性.

负整数的结果>>>>>整数除(div)的结果将不同.

另请注意,使用无符号右移位运算符>>>可能会使您避免某些整数溢出问题.

div(x,y)

÷(x,y)

来自欧几里德分部的商.计算x/y,截断为整数.

julia> 3/2 # returns a floating point number
1.5

julia> julia> 4/2
2.0

julia> 3//2 # returns a Rational
3//2  

# now integer divison
julia> div(3, 2) # returns an integer
1

julia> 3 ÷ 2 # this is the same as div(3, 2)
1

julia> 9 >> 1 # this divides a positive integer by 2
4

julia> 9 >>> 1 # this also divides a positive integer by 2
4
# results with negative numbers
julia> -5 ÷ 2
-2

julia> -5 >> 1 
-3

julia> -5 >>> 1
9223372036854775805

# results with overflowing (wrapping-around) argument
julia> (Int8(127) + Int8(3)) ÷ 2  # 127 is the largest Int8 integer 
-63

julia> (Int8(127) + Int8(3)) >> 1
-63

julia> (Int8(127) + Int8(3)) >>> 1 # still gives 65 (130 ÷ 2)
65
Run Code Online (Sandbox Code Playgroud)

您可以使用@code_native宏来查看如何将内容编译为本机代码.请不要忘记更多的说明并不一定意味着更慢,虽然在这里是这样的.

julia> f(a) = a ÷ 2
f (generic function with 2 methods)

julia> g(a) = a >> 1
g (generic function with 2 methods)

julia> h(a) = a >>> 1
h (generic function with 1 method)

julia> @code_native f(5)
    .text
; Function f {
; Location: REPL[61]:1
; Function div; {
; Location: REPL[61]:1
    movq    %rdi, %rax
    shrq    $63, %rax
    leaq    (%rax,%rdi), %rax
    sarq    %rax
;}
    retq
    nop
;}

julia> @code_native g(5)
    .text
; Function g {
; Location: REPL[62]:1
; Function >>; {
; Location: int.jl:448
; Function >>; {
; Location: REPL[62]:1
    sarq    %rdi
;}}
    movq    %rdi, %rax
    retq
    nopw    (%rax,%rax)
;}

julia> @code_native h(5)
    .text
; Function h {
; Location: REPL[63]:1
; Function >>>; {
; Location: int.jl:452
; Function >>>; {
; Location: REPL[63]:1
    shrq    %rdi
;}}
    movq    %rdi, %rax
    retq
    nopw    (%rax,%rax)
;}
Run Code Online (Sandbox Code Playgroud)