Skip to content

Commit

Permalink
Make var(Range) type stable
Browse files Browse the repository at this point in the history
Fixes #22773
  • Loading branch information
andreasnoack committed Jul 12, 2017
1 parent 51b837b commit 6f9c5a2
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 9 deletions.
20 changes: 11 additions & 9 deletions base/statistics.jl
Original file line number Diff line number Diff line change
Expand Up @@ -210,22 +210,24 @@ varm(iterable, m::Number; corrected::Bool=true) =
## variances over ranges

function varm(v::Range, m::Number)
f = first(v) - m
s = step(v)
l = length(v)
f = first(v) - m
s = step(v)
l = length(v)
vv = f^2 * l / (l - 1) + f * s * l + s^2 * l * (2 * l - 1) / 6
if l == 0 || l == 1
return NaN
return typeof(vv)(NaN)
end
return f^2 * l / (l - 1) + f * s * l + s^2 * l * (2 * l - 1) / 6
return vv
end

function var(v::Range)
s = step(v)
l = length(v)
s = step(v)
l = length(v)
vv = abs2(s) * (l + 1) * l / 12
if l == 0 || l == 1
return NaN
return typeof(vv)(NaN)
end
return abs2(s) * (l + 1) * l / 12
return vv
end


Expand Down
12 changes: 12 additions & 0 deletions test/statistics.jl
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,18 @@ X = [2 3 1 -1; 7 4 5 -4]
@test isnan(var(1:1))
@test isnan(var(1:-1))

@test @inferred(var(1.0:8.0)) == 6.
@test varm(1.0:8.0,1.0) == varm(collect(1.0:8.0),1)
@test isnan(varm(1.0:1.0,1.0))
@test isnan(var(1.0:1.0))
@test isnan(var(1.0:-1.0))

@test @inferred(var(1.0f0:8.0f0)) == 6.f0
@test varm(1.0f0:8.0f0,1.0f0) == varm(collect(1.0f0:8.0f0),1)
@test isnan(varm(1.0f0:1.0f0,1.0f0))
@test isnan(var(1.0f0:1.0f0))
@test isnan(var(1.0f0:-1.0f0))

@test varm([1,2,3], 2) 1.
@test var([1,2,3]) 1.
@test var([1,2,3]; corrected=false) 2.0/3
Expand Down

0 comments on commit 6f9c5a2

Please sign in to comment.