首页 > 解决方案 > 尝试添加不同类型的数量时出现 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,我是否经常需要摆弄函数之间使用和传递的数据类型?

标签: julia

解决方案


问题是 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

推荐阅读