From 857debf0217aae9e38bf0050c7c755cbdac1d970 Mon Sep 17 00:00:00 2001 From: Samuel Albert Date: Wed, 21 Apr 2021 17:07:26 -0400 Subject: [PATCH] improvements suggested by David Widmann --- src/univariate/continuous/laplace.jl | 38 +++++----------------------- 1 file changed, 6 insertions(+), 32 deletions(-) diff --git a/src/univariate/continuous/laplace.jl b/src/univariate/continuous/laplace.jl index e853384e0c..ebd3945ea8 100644 --- a/src/univariate/continuous/laplace.jl +++ b/src/univariate/continuous/laplace.jl @@ -114,36 +114,10 @@ rand(rng::AbstractRNG, d::Laplace) = #### Fitting -function fit_mle(::Type{<:Laplace}, x::AbstractArray{T}) where {T<:Real} - μ = median(x) - θ = zero(T) - for v ∈ x - θ += abs(v - μ) - end - θ /= length(x) - return Laplace(μ, θ) -end - -function fit_mle(::Type{<:Laplace}, x::AbstractArray{T}, w::AbstractArray{T}) where {T <: Real} - sp = sortperm(x) - n = length(x) - sw = sum(w) - highsum = sw - lowsum = zero(T) - idx = 0 - for i = 1:n - lowsum += w[sp[i]] - highsum -= w[sp[i]] - if lowsum >= highsum - idx = sp[i] - break - end - end - μ = x[idx] - θ = zero(T) - for i = 1:length(x) - θ += w[i] * abs(x[i] - μ) - end - θ /= sw - return Laplace(μ, θ) +function fit_mle(::Type{<:Laplace}, x::AbstractArray{<:Real}) + xc = similar(x) + copyto!(xc, x) + m = median!(xc) + xc .= abs.(x .- m) + return Laplace(m, mean(xc)) end