Skip to content

Commit

Permalink
Make median non-mutating on arrays.
Browse files Browse the repository at this point in the history
Due to a change in the behaviour of `mapslices` (JuliaLang#16260), `median(X,k)` would mutate the underlying array. Fixes JuliaLang#17153.
  • Loading branch information
simonbyrne authored and mfasi committed Sep 5, 2016
1 parent 4da6c4f commit bc733d8
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 4 deletions.
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,8 @@ Breaking changes
If a reshaped copy is needed, use `copy(reshape(a))` or `copy!` to a new array of
the desired shape ([#4211]).

* `mapslices` will always pass a view, so passing mutating functions will mutate the underlying array ([#16260])

* Local variables and arguments are represented in lowered code as numbered `Slot`
objects instead of as symbols ([#15609]).

Expand Down
5 changes: 3 additions & 2 deletions base/statistics.jl
Original file line number Diff line number Diff line change
Expand Up @@ -490,9 +490,10 @@ function median!{T}(v::AbstractVector{T})
end
end
median!{T}(v::AbstractArray{T}) = median!(vec(v))

median{T}(v::AbstractArray{T}) = median!(copy!(Array(T, length(v)), v))
median{T}(v::AbstractArray{T}, region) = mapslices(median!, v, region)

median!{T}(v::AbstractArray{T}, region) = mapslices(median!, v, region)
median{T}(v::AbstractArray{T}, region) = median!(copy(v), region)

# for now, use the R/S definition of quantile; may want variants later
# see ?quantile in R -- this is type 7
Expand Down
7 changes: 5 additions & 2 deletions test/statistics.jl
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,10 @@ end
@test median([1.,-1.,Inf,-Inf]) == 0.0
@test isnan(median([-Inf,Inf]))

@test all(median([2 3 1 -1; 7 4 5 -4], 2) .== [1.5, 4.5])
@test all(median([2 3 1 -1; 7 4 5 -4], 1) .== [4.5 3.5 3.0 -2.5])
X = [2 3 1 -1; 7 4 5 -4]
@test all(median(X, 2) .== [1.5, 4.5])
@test all(median(X, 1) .== [4.5 3.5 3.0 -2.5])
@test X == [2 3 1 -1; 7 4 5 -4] # issue #17153

@test_throws ArgumentError median([])
@test isnan(median([NaN]))
Expand All @@ -44,6 +46,7 @@ end
@test median!([1 2 3 4]) == 2.5
@test median!([1 2; 3 4]) == 2.5


@test invoke(median, (AbstractVector,), 1:10) == median(1:10) == 5.5

# mean
Expand Down

0 comments on commit bc733d8

Please sign in to comment.