# Fitting a Weibull distribution to values

**URL:** <https://discourse.julialang.org/t/fitting-a-weibull-distribution-to-values/30600>\
**Category:** General Usage\
**Tags:** question\
**Created:** [November 1, 2019, 6:38pm UTC](https://discourse.julialang.org/t/fitting-a-weibull-distribution-to-values/30600 "2019-11-01T18:38:41Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![ramonz](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ramonz/32/548_2.png) [@ramonz](https://discourse.julialang.org/u/ramonz)\
**Post date:** [November 1, 2019, 6:38pm UTC](https://discourse.julialang.org/t/fitting-a-weibull-distribution-to-values/30600/1 "2019-11-01T18:38:41Z")

</div>

Hello again

I would like to fit a set of values to a Weibull distribution but the fitting is still not implemented in the Distributions.jl package for this type of Distribution [Distribution Fitting · Distributions.jl](https://juliastats.org/Distributions.jl/stable/fit/).

Any suggestions?

---

<div class="post-metadata">

**Author:** ![non-Jedi](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/non-jedi/32/3645_2.png) [@non-Jedi](https://discourse.julialang.org/u/non-Jedi)\
**Post date:** [November 1, 2019, 7:10pm UTC](https://discourse.julialang.org/t/fitting-a-weibull-distribution-to-values/30600/2 "2019-11-01T19:10:35Z")

</div>

Here’s what I hacked together when I needed it a couple weeks ago. Feel free to use it under [CC0](https://creativecommons.org/publicdomain/zero/1.0/legalcode):

```julia
using Distributions, Roots

function implicit_k_estimator(x, k::Number)
    xᵏ = x.^k
    lnx = log.(x)
    sum(xᵏ .* lnx) / sum(xᵏ) - inv(k) - sum(lnx) / length(x)
end#function

explicit_λ_estimator(k::Number, x) = (sum(x.^k) / length(x))^(1/k)

function Distributions.fit_mle(::Type{Weibull}, x::AbstractArray)
    f = k -> implicit_k_estimator(x, k)
    k = find_zero(f, oneunit(eltype(x)), Order2())
    λ = explicit_λ_estimator(k, x)
    Weibull(k, λ)
end#function

```

No guarantees about correctness of course; I followed the section on  
estimators from the Weibull Wikipedia article, and it worked for my  
purposes. After defining the above functions, the `fit` function  
should work for `Weibull` distribution.

---

<div class="post-metadata">

**Author:** ![ramonz](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ramonz/32/548_2.png) [@ramonz](https://discourse.julialang.org/u/ramonz)\
**Post date:** [November 1, 2019, 7:11pm UTC](https://discourse.julialang.org/t/fitting-a-weibull-distribution-to-values/30600/3 "2019-11-01T19:11:51Z")

</div>

Thanks, I´ll give it a try.
