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

时间:2018-11-25 07:30:11

标签: julia

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

1 个答案:

答案 0 :(得分:12)

为获得更好的性能,您需要为此进行整数除法(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

您可以使用@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)
;}
相关问题