Skip to content

Commit f8a7da2

Browse files
authored
Avoid undesired promotions in entropy calculations (#925)
* Avoid undesired promotions in `entropy` calculations * Clean file
1 parent 4c9e559 commit f8a7da2

File tree

2 files changed

+11
-1
lines changed

2 files changed

+11
-1
lines changed

src/scalarstats.jl

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -740,7 +740,13 @@ function entropy(p)
740740
return -sum(xlogx, p)
741741
end
742742

743-
entropy(p, b::Real) = entropy(p) / log(b)
743+
function entropy(p, b::Real)
744+
e = entropy(p)
745+
# Promote explicitly before applying `log` to avoid undesired promotions
746+
# with `log(b)::Float64` arising from `b::Int` (ref: #924)
747+
_b = first(promote(b, e))
748+
return e / log(_b)
749+
end
744750

745751
"""
746752
renyientropy(p, α)

test/scalarstats.jl

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,6 +260,10 @@ it = (xᵢ for xᵢ in x)
260260
@test @inferred(entropy([1//2, 1//2], 2)) 1.0
261261
@test @inferred(entropy([0.2, 0.3, 0.5], 2)) 1.4854752972273344
262262

263+
# issue #924
264+
@test @inferred(entropy([0.5f0, 0.5f0], 2)) isa Float32
265+
@test @inferred(entropy([0.5f0, 0.5f0], MathConstants.e)) isa Float32
266+
263267
@test_throws ArgumentError @inferred(entropy(Float64[]))
264268
@test_throws ArgumentError @inferred(entropy(Int[]))
265269

0 commit comments

Comments
 (0)