这在几种编程语言中很常见,不仅仅是 Julia:求幂比减法或求反具有更高的优先级。对于 Julia,您可以在此处查看运算符优先级列表:https://docs.julialang.org/en/v1/manual/mathematical-operations/#Operator-Precedence-and-Associativity-1。
因此,-1^2 不会产生您可能天真的期望的结果:
julia> -1^2
-1
为了覆盖默认优先级,只需根据需要使用括号:
julia> (-1)^2
1
正如 Lyndon White 在 a comment 中所建议的那样,可视化表达式中操作优先级的一种好方法是引用它
julia> :(-1 ^ 2)
:(-(1 ^ 2))
julia> :((-1) ^ 2)
:((-1) ^ 2)
和dump 可以看到完整的AST:
julia> dump(:(-1 ^ 2))
Expr
head: Symbol call
args: Array{Any}((2,))
1: Symbol -
2: Expr
head: Symbol call
args: Array{Any}((3,))
1: Symbol ^
2: Int64 1
3: Int64 2
julia> dump(:((-1) ^ 2))
Expr
head: Symbol call
args: Array{Any}((3,))
1: Symbol ^
2: Int64 -1
3: Int64 2
这里你可以注意到,在第一种情况下,求幂在求反之前进行,在使用括号的第二种情况下,求反在求幂之前。
在 Julia 中查看表达式如何降低的另一种巧妙方法是使用 Meta.lower 函数:
julia> Meta.lower(Main, :(-1 ^ 2) )
:($(Expr(:thunk, CodeInfo(
@ none within `top-level scope'
1 ─ %1 = Core.apply_type(Base.Val, 2)
│ %2 = (%1)()
│ %3 = Base.literal_pow(^, 1, %2)
│ %4 = -%3
└── return %4
))))
julia> Meta.lower(Main, :((-1) ^ 2) )
:($(Expr(:thunk, CodeInfo(
@ none within `top-level scope'
1 ─ %1 = Core.apply_type(Base.Val, 2)
│ %2 = (%1)()
│ %3 = Base.literal_pow(^, -1, %2)
└── return %3
))))
对于您的特定问题,您可以这样做
function computeequation()
result = 0
for k = 1:1000_000
result = result + ((-1) ^ (k + 1))/((2 * k) - 1)
end
return 4 * result
end