尝试添加不同类型的数字时出现MethodError

function random_step(x, dx)
    num=randn(1)
    return x + num*dx
end

random_step(1, 1)

运行此代码给了我:

julia> random_step(1, 1)
ERROR: MethodError: no method matching +(::Int32, ::Array{Float64,1})       
For element-wise addition, use broadcasting with dot syntax: scalar .+ array
Closest candidates are:
  +(::Any, ::Any, ::Any, ::Any...) at operators.jl:538
  +(::T, ::T) where T<:Union{Int128, Int16, Int32, Int64, Int8, UInt128, UInt16, UInt32, UInt64, UInt8} at int.jl:86
  +(::Union{Int16, Int32, Int8}, ::BigInt) at gmp.jl:531
  ...
Stacktrace:
 [1] random_step(::Int32, ::Int32) at .REPL[1]:3
 [2] top-level scope at REPL[2]:1

所以我假设当我输入 1 时,数据类型不是 randn 的 Float64。那么如何在 julia 中快速创建变量并控制它们的数据类型?我经常需要这样做来调试代码。这对我继续与朱莉娅一起会是一个问题吗?我认为它就像 python,我是否经常需要摆弄函数之间使用和传递的数据类型?

回答

问题是 randn(1) 生成的是 Array{Float64,1} 而不是 Float64。

如果添加两个标量,即使它们的类型不同,它们中的一个(或两个)也会按预期提升,例如:

 julia> 1 + 1.0
 2.0

但是,添加一个数组和一个标量并没有明确的规则,这正是您要尝试做的。

什么地方出了错?

函数 randn(1) 创建一个数组,其中包含 Float64 类型的元素,而不仅仅是一个元素。

您可以查看 randn 的文档并了解原因:

help?> randn
search: randn rand transcode macroexpand @macroexpand1 @macroexpand CartesianIndex CartesianIndices

  randn([rng=GLOBAL_RNG], [T=Float64], [dims...])

  Generate a normally-distributed random number of type T with mean 0 and standard deviation 1. Optionally
  generate an array of normally-distributed random numbers.

因此,通过使用 (1) 调用,您指定您想要一个一维数组,其中唯一的维度有一个元素。

如何解决?

您应该将您的功能定义为

function random_step(x, dx)
    num=randn()
    return x + num*dx
end

请注意,我正在调用rand(),它返回一个 Float64 而不是rand(1)返回一个包含 Float64 类型元素的数组。

这样做,您可以看到您的示例有效:

julia> function random_step(x, dx)
           num=randn()
           return x + num*dx
       end
random_step (generic function with 1 method)

julia> random_step(1, 1)
1.5813972833750205


以上是尝试添加不同类型的数字时出现MethodError的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>