Struggling_Student
Struggling_Student

Reputation: 464

Median absolute deviation in Julia

I approximated pi using the Monte Carlo method.
I am having troubles calculating the Median absolute deviation of my results (see code below).
My guess is that there is already a function in Julia that does this but unfortunately I have no idea how to implement it in my code.

enter image description here

for i in 1:5
   picircle(1000)
end
3.0964517741129436
3.152423788105947
3.1284357821089457
3.1404297851074463
3.0904547726136933

Upvotes: 1

Views: 599

Answers (1)

cbk
cbk

Reputation: 4370

As MarcMush mentioned in the comments, StatsBase exports the mad function, which as we can see from the docstring

help?> mad
search: mad mad! maxad muladd mapreduce meanad ismarked mapfoldr mapfoldl mean_and_var mean_and_std mean_and_cov macroexpand

  mad(x; center=median(x), normalize=true)

  Compute the median absolute deviation (MAD) of collection x around center (by default, around the median).

  If normalize is set to true, the MAD is multiplied by 1 / quantile(Normal(), 3/4) ≈ 1.4826, in order to obtain a consistent
  estimator of the standard deviation under the assumption that the data is normally distributed.

so

julia> A = randn(10000);

julia> using StatsBase

julia> mad(A, normalize=false)
0.6701649037518176

or alternatively, if you don't want the StatsBase dependency, then you can just calculate it directly with (e.g.)

julia> using Statistics

julia> median(abs.(A .- median(A)))
0.6701649037518176

which gives an identical result

Upvotes: 2

Related Questions