据我所知,以下应该是等效的:
julia> rand(2).^2
2-element Array{Float64,1}:
0.164246
0.47107
julia> @. rand(2)^2
ERROR: DimensionMismatch("Cannot multiply two vectors")
Stacktrace:
[1] power_by_squaring(::Array{Float64,1}, ::Int64) at ./intfuncs.jl:169
[2] broadcast(::##65#66) at ./sysimg.jl:86
这个也一样:
julia> 1./rand(2)
2-element Array{Float64,1}:
1.93886
3.01834
julia> @. 1/rand(2)
ERROR: MethodError: no method matching /(::Int64, ::Array{Float64,1})
Closest candidates are:
/(::PyCall.PyObject, ::Any) at /home/simon/.julia/v0.6/PyCall/src/pyoperators.jl:11
/(::Union{Int128, Int16, Int32, Int64, Int8, UInt128, UInt16, UInt32, UInt64, UInt8}, ::Union{Int128, Int16, Int32, Int64, Int8, UInt128, UInt16, UInt32, UInt64, UInt8}) at int.jl:38
/(::Union{Int16, Int32, Int64, Int8, UInt16, UInt32, UInt64, UInt8}, ::BigInt) at gmp.jl:381
...
Stacktrace:
[1] broadcast(::##69#70) at ./sysimg.jl:86
我到底做错了什么?
最佳答案
问题是这样你也广播 rand
, @.
宏适用于所有函数调用,包括二元运算符调用(即 1 + 1
被解析为 +(1, 1)
)
@macroexpand
宏来查看宏调用的结果表达式。 $(f(x))
广播的函数调用 (@.
)。 julia> @macroexpand @. rand(2)^2
:(^.(rand.(2), 2)) # same as: rand.(2).^2
julia> eval(ans)
ERROR: DimensionMismatch("Cannot multiply two vectors")
julia> @macroexpand @. $(rand(2))^2
:(^.(rand(2), 2)) # same as: rand(2).^2
julia> eval(ans)
2-element Array{Float64,1}:
0.26266
0.326033
julia> @macroexpand @. 1 / rand(2)
:(/.(1, rand.(2))) # same as: 1 ./ rand.(2)
julia> eval(ans)
ERROR: MethodError: no method matching /(::Int64, ::Array{Float64,1})
julia> @macroexpand @. 1 / $(rand(2))
:(/.(1, rand(2))) # same as: 1 ./ rand(2)
julia> eval(ans)
2-element Array{Float64,1}:
37.1023
1.08004
关于 Julia 的@。宏和二元运算符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48572871/