gpt4 book ai didi

Julia 的@。宏和二元运算符

转载 作者:行者123 更新时间:2023-12-01 04:37:47 24 4
gpt4 key购买 nike

据我所知,以下应该是等效的:

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

我到底做错了什么?

最佳答案

help?> @.

@. expr

Convert every function call or operator in expr into a "dot call" (e.g. convert f(x) to f.(x)), and convert every assignment in expr to a "dot assignment" (e.g. convert += to .+=).

If you want to avoid adding dots for selected function calls in expr, splice those function calls in with $.

For example, @. sqrt(abs($sort(x))) is equivalent to sqrt.(abs.(sort(x))) (no dot for sort).



问题是这样你也在广播 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/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com