New submission from Reed <rea...@gmail.com>:
If a float32 Numpy array is passed to statistics.variance(), an assertion failure occurs. For example: import statistics import numpy as np x = np.array([1, 2], dtype=np.float32) statistics.variance(x) The assertion error is: assert T == U and count == count2 Even if you convert x to a list with `x = list(x)`, the issue still occurs. The issue is caused by the following lines in statistics.py (https://github.com/python/cpython/blob/ec007cb43faf5f33d06efbc28152c7fdcb2edb9c/Lib/statistics.py#L687-L691): T, total, count = _sum((x-c)**2 for x in data) # The following sum should mathematically equal zero, but due to rounding # error may not. U, total2, count2 = _sum((x-c) for x in data) assert T == U and count == count2 When a float32 Numpy value is squared in the term (x-c)**2, it turns into a float64 value, causing the `T == U` assertion to fail. I think the best way to fix this would be to replace (x-c)**2 with (x-c)*(x-c). This fix would no longer assume the input's ** operator returns the same type. ---------- components: Library (Lib) messages: 359323 nosy: reed priority: normal severity: normal status: open title: Assertion failure when calling statistics.variance() on a float32 Numpy array type: behavior versions: Python 3.8 _______________________________________ Python tracker <rep...@bugs.python.org> <https://bugs.python.org/issue39218> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com