Skip to content

Commit 543db4b

Browse files
authored
Fixes issue of std of hist with negative content (#142)
* fix: handle negative variance in standard deviation calculation for Hist1D * fix: add tests for handling negative content in Hist1D * update the test
1 parent f70d033 commit 543db4b

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

src/hist1d.jl

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,10 @@ by the bin counts.
157157
When the histogram is `Hist2D`, return tuple instead, e.g `(mean(project(h, :x)), mean(project(h, :y)))` etc.
158158
"""
159159
Statistics.mean(h::Hist1D) = Statistics.mean(bincenters(h), Weights(bincounts(h)))
160-
Statistics.std(h::Hist1D) = Statistics.var(bincenters(h), Weights(bincounts(h)); corrected=false) |> sqrt
160+
Statistics.std(h::Hist1D) = begin
161+
var = Statistics.var(bincenters(h), Weights(bincounts(h)); corrected=false)
162+
var < 0 ? NaN : sqrt(var)
163+
end
161164
Statistics.median(h::Hist1D) = Statistics.median(bincenters(h), Weights(bincounts(h)))
162165
Statistics.quantile(h::Hist1D, p) = Statistics.quantile(bincenters(h), Weights(bincounts(h)), p)
163166

test/runtests.jl

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -639,4 +639,6 @@ end
639639
@test FHist.effective_entries(h) 2.76923076923077
640640
end
641641

642+
include("test-algebraic-content.jl")
643+
642644
include("hdf5.jl")

test/test-algebraic-content.jl

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
using Test
2+
using FHist
3+
using FHist.Statistics
4+
@testset "Negative content" begin
5+
h0 = Hist1D([1, 3, 4, 5, 6, 7, 3]; binedges = range(0, 10, 5))
6+
original_mean = mean(h0)
7+
h0.bincounts .-= mean(h0.bincounts) # This makes sum of weights ≈ 0
8+
@test abs(sum(h0.bincounts)) < 1e-10 # Verify weights sum to approximately zero
9+
@test isnan(std(h0)) # Std should be NaN with near-zero sum of weights
10+
end

0 commit comments

Comments
 (0)