我有一个奇数n
,希望使用(n+1)/2
作为数组索引。计算指数的最佳方法是什么?我刚刚想到使用Int((n+1)/2)
、round(Int, (n+1)/2))
和Int((n+1)//2)
。哪一个更好,还是我不需要太担心他们?
为了获得更好的性能,您需要整数除法(div
或÷
(。/
给出整数参数的浮点结果。CCD_ 9给出的CCD_。因此,您需要编写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)
;}