You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The mean function does not consistently treat empty iterators, arrays, and general iterables. None of the current behaviors are documented.
The behavior for ranges (AbstractRange{<:Real}) is to return NaN:
julia>using Statistics
julia>mean(1:0)
NaN
The behavior for arrays is to throw an error:
julia>mean([])
ERROR: MethodError: no method matching zero(::Type{Any})
The behavior for general iterables is to throw a different error:
julia>mean(x for x in ())
ERROR: ArgumentError: reducing over an empty collection is not allowed
The text was updated successfully, but these errors were encountered:
yurivish
changed the title
mean has inconsistent behavior when passed an empty collectionmean has inconsistent behavior when passed an empty collection
Jun 27, 2022
While I agree that the user experience isn't optimal, note that this isn't specific to mean: sum exhibits identical behaviors for these examples. It comes down to whether the correct output type is knowable based on the element type of the input. Range literals always have a real, concrete element type, so zero(T) is defined, which means we can return zero(T) / 0 for the mean. The same is true of Int[], which is why @jishnub's examples match. The same is not true of [], which has element type Any, and thus you get the MethodError noted in the OP. The reasoning behind the ArgumentError for the generator is the same, and that error is arguably more informative for the user than the MethodError.
I'd vote that the documentation for sum and mean both be updated to note that an error is thrown for empty collections unless the element type supports zero (or the init keyword is passed in the case of sum), without specifying what the precise error is.
The
mean
function does not consistently treat empty iterators, arrays, and general iterables. None of the current behaviors are documented.The behavior for ranges (
AbstractRange{<:Real}
) is to returnNaN
:The behavior for arrays is to throw an error:
The behavior for general iterables is to throw a different error:
The text was updated successfully, but these errors were encountered: