debugging Monte Carlo程序在Julia中引发方法错误

v2g6jxz6  于 2022-12-19  发布在  其他
关注(0)|答案(1)|浏览(152)

我正在运行这段代码,但是它显示了一个方法错误。有人能帮帮我吗?
代码:

function lsmc_am_put(S, K, r, σ, t, N, P)
    Δt = t / N
    R = exp(r * Δt)
    T = typeof(S * exp(-σ^2 * Δt / 2 + σ * √Δt * 0.1) / R)
    X = Array{T}(N+1, P)

    for p = 1:P
        X[1, p] = x = S
        for n = 1:N
            x *= R * exp(-σ^2 * Δt / 2 + σ * √Δt * randn())
            X[n+1, p] = x
        end
    end

    V = [max(K - x, 0) / R for x in X[N+1, :]]

    for n = N-1:-1:1
        I = V .!= 0
        A = [x^d for d = 0:3, x in X[n+1, :]]
        β = A[:, I]' \ V[I]
        cV = A' * β
        for p = 1:P
            ev = max(K - X[n+1, p], 0)
            if I[p] && cV[p] < ev
                V[p] = ev / R
            else
                V[p] /= R
            end
        end
    end

    return max(mean(V), K - S)
end

lsmc_am_put(100, 90, 0.05, 0.3, 180/365, 1000, 10000)

错误:

MethodError: no method matching (Array{Float64})(::Int64, ::Int64)
Closest candidates are:
  (Array{T})(::LinearAlgebra.UniformScaling, ::Integer, ::Integer) where T at /Volumes/Julia-1.8.3/Julia-1.8.app/Contents/Resources/julia/share/julia/stdlib/v1.8/LinearAlgebra/src/uniformscaling.jl:508
  (Array{T})(::Nothing, ::Any...) where T at baseext.jl:45
  (Array{T})(::UndefInitializer, ::Int64) where T at boot.jl:473
  ...
Stacktrace:
 [1] lsmc_am_put(S::Int64, K::Int64, r::Float64, σ::Float64, t::Float64, N::Int64, P::Int64)
   @ Main ./REPL[39]:5
 [2] top-level scope
   @ REPL[40]:1

我试了这个代码,我期待一个数字答案,但这个错误出现了。我试图在谷歌上查找,但我没有找到任何符合我的情况。

nvbavucw

nvbavucw1#

错误发生在您写入X = Array{T}(N+1, P)的位置。如果需要Vector,请改用以下方法之一:

julia> Array{Float64, 1}([1,2,3])
3-element Vector{Float64}:
 1.0
 2.0
 3.0

julia> Vector{Float64}([1, 2, 3])
3-element Vector{Float64}:
 1.0
 2.0
 3.0

在你的例子中,你应该写X = Array{T,1}([N+1, P])X = Vector{T}([N+1, P]),但是因为你的代码中有这样一个X[1, p] = x = S表达式,我猜你的意思是初始化一个2D数组并通过算法更新它的元素,为此,你可以像下面这样定义X

X = zeros(Float64, N+1, P)

# Or

X = Array{Float64, 2}(undef, N+1, P)

因此,我在您的代码中尝试了以下内容:

# I just changed the definition of `X` in your code like the following
X = Array{T, 2}(undef, N+1, P)

#And the result of the code was:
julia> lsmc_am_put(100, 90, 0.05, 0.3, 180/365, 1000, 10000)
3.329213731484463

相关问题