Fix statistics sensor mean and median when only one sample is available. (#11180)
* Fix statistics sensor mean and median when only one sample is available. With only one data point stddev and variance throw an exception. This would clear the (valid) mean and median calculations. Separate the try..catch blocks for one-or-more and two-or-more stats so that this doesn't happen. Test this with a new sampling_size_1 test. * test_statistics trivial whitespace fix
This commit is contained in:
1 parent
061395d2f8
commit
ef22a6e18d
2 files changed
+41
-3
No files matched your search
@@ -175,15 +175,20 @@ class StatisticsSensor(Entity):
|
||||
self._purge_old()
|
||||
|
||||
if not self.is_binary:
|
||||
try:
|
||||
try: # require only one data point
|
||||
self.mean = round(statistics.mean(self.states), 2)
|
||||
self.median = round(statistics.median(self.states), 2)
|
||||
except statistics.StatisticsError as err:
|
||||
_LOGGER.error(err)
|
||||
self.mean = self.median = STATE_UNKNOWN
|
||||
|
||||
try: # require at least two data points
|
||||
self.stdev = round(statistics.stdev(self.states), 2)
|
||||
self.variance = round(statistics.variance(self.states), 2)
|
||||
except statistics.StatisticsError as err:
|
||||
_LOGGER.error(err)
|
||||
self.mean = self.median = STATE_UNKNOWN
|
||||
self.stdev = self.variance = STATE_UNKNOWN
|
||||
|
||||
if self.states:
|
||||
self.total = round(sum(self.states), 2)
|
||||
self.min = min(self.states)
|
||||
|
||||
Reference in new issue
Block a user