bpo-40290: Add zscore() to statistics.NormalDist. (GH-19547)
diff --git a/Lib/statistics.py b/Lib/statistics.py
index 1e95c0b..9beafb3 100644
--- a/Lib/statistics.py
+++ b/Lib/statistics.py
@@ -999,6 +999,17 @@
x2 = (a - b) / dv
return 1.0 - (fabs(Y.cdf(x1) - X.cdf(x1)) + fabs(Y.cdf(x2) - X.cdf(x2)))
+ def zscore(self, x):
+ """Compute the Standard Score. (x - mean) / stdev
+
+ Describes *x* in terms of the number of standard deviations
+ above or below the mean of the normal distribution.
+ """
+ # https://www.statisticshowto.com/probability-and-statistics/z-score/
+ if not self._sigma:
+ raise StatisticsError('zscore() not defined when sigma is zero')
+ return (x - self._mu) / self._sigma
+
@property
def mean(self):
"Arithmetic mean of the normal distribution."
diff --git a/Lib/test/test_statistics.py b/Lib/test/test_statistics.py
index a9a427b..0e46a71 100644
--- a/Lib/test/test_statistics.py
+++ b/Lib/test/test_statistics.py
@@ -2602,6 +2602,21 @@
with self.assertRaises(self.module.StatisticsError):
NormalDist(1, 0).overlap(X) # left operand sigma is zero
+ def test_zscore(self):
+ NormalDist = self.module.NormalDist
+ X = NormalDist(100, 15)
+ self.assertEqual(X.zscore(142), 2.8)
+ self.assertEqual(X.zscore(58), -2.8)
+ self.assertEqual(X.zscore(100), 0.0)
+ with self.assertRaises(TypeError):
+ X.zscore() # too few arguments
+ with self.assertRaises(TypeError):
+ X.zscore(1, 1) # too may arguments
+ with self.assertRaises(TypeError):
+ X.zscore(None) # non-numeric type
+ with self.assertRaises(self.module.StatisticsError):
+ NormalDist(1, 0).zscore(100) # sigma is zero
+
def test_properties(self):
X = self.module.NormalDist(100, 15)
self.assertEqual(X.mean, 100)