Statistics.jl icon indicating copy to clipboard operation
Statistics.jl copied to clipboard

mean! may return incorrect results

Open yurivish opened this issue 4 years ago • 2 comments

I noticed that the mean! function does not properly consider that its arguments may alias each other. In some such cases the result from mean! is not correct:

julia> let a = [1 2 3]
           mean!(a, a)
       end
1×3 Array{Int64,2}:
 0  0  0

julia> let a = [1 2 3]
           mean!(copy(a), a)
       end
1×3 Array{Int64,2}:
 1  2  3

julia> versioninfo()
Julia Version 1.5.3
Commit 788b2c77c1 (2020-11-09 13:37 UTC)
Platform Info:
  OS: macOS (x86_64-apple-darwin18.7.0)
  CPU: Intel(R) Core(TM) i9-9980HK CPU @ 2.40GHz
  WORD_SIZE: 64
  LIBM: libopenlibm
  LLVM: libLLVM-9.0.1 (ORCJIT, skylake)

yurivish avatar Jan 24 '21 22:01 yurivish

Viewing the definition of mean!. The result of the operation mean!(r, v) is written in r. Therefore it seems logical to me that if you use the same object as variable r and as variable v, the result is unpredictable.

I have seen that this also happens with the sum! function.

https://stackoverflow.com/questions/69963082/mean-may-return-incorrect-results

josemanuel22 avatar Nov 01 '21 10:11 josemanuel22

Could you file the equivalent PR for sum against Julia Base? Then once a decision is made there we can apply the same change here. See https://github.com/JuliaLang/julia/issues/39385.

nalimilan avatar Nov 20 '21 17:11 nalimilan

Closed by https://github.com/JuliaStats/Statistics.jl/pull/96

andreasnoack avatar May 28 '24 11:05 andreasnoack