test_statistics.py 119 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044
  1. """Test suite for statistics module, including helper NumericTestCase and
  2. approx_equal function.
  3. """
  4. import bisect
  5. import collections
  6. import collections.abc
  7. import copy
  8. import decimal
  9. import doctest
  10. import itertools
  11. import math
  12. import pickle
  13. import random
  14. import sys
  15. import unittest
  16. from test import support
  17. from test.support import import_helper, requires_IEEE_754
  18. from decimal import Decimal
  19. from fractions import Fraction
  20. # Module to be tested.
  21. import statistics
  22. # === Helper functions and class ===
  23. def sign(x):
  24. """Return -1.0 for negatives, including -0.0, otherwise +1.0."""
  25. return math.copysign(1, x)
  26. def _nan_equal(a, b):
  27. """Return True if a and b are both the same kind of NAN.
  28. >>> _nan_equal(Decimal('NAN'), Decimal('NAN'))
  29. True
  30. >>> _nan_equal(Decimal('sNAN'), Decimal('sNAN'))
  31. True
  32. >>> _nan_equal(Decimal('NAN'), Decimal('sNAN'))
  33. False
  34. >>> _nan_equal(Decimal(42), Decimal('NAN'))
  35. False
  36. >>> _nan_equal(float('NAN'), float('NAN'))
  37. True
  38. >>> _nan_equal(float('NAN'), 0.5)
  39. False
  40. >>> _nan_equal(float('NAN'), Decimal('NAN'))
  41. False
  42. NAN payloads are not compared.
  43. """
  44. if type(a) is not type(b):
  45. return False
  46. if isinstance(a, float):
  47. return math.isnan(a) and math.isnan(b)
  48. aexp = a.as_tuple()[2]
  49. bexp = b.as_tuple()[2]
  50. return (aexp == bexp) and (aexp in ('n', 'N')) # Both NAN or both sNAN.
  51. def _calc_errors(actual, expected):
  52. """Return the absolute and relative errors between two numbers.
  53. >>> _calc_errors(100, 75)
  54. (25, 0.25)
  55. >>> _calc_errors(100, 100)
  56. (0, 0.0)
  57. Returns the (absolute error, relative error) between the two arguments.
  58. """
  59. base = max(abs(actual), abs(expected))
  60. abs_err = abs(actual - expected)
  61. rel_err = abs_err/base if base else float('inf')
  62. return (abs_err, rel_err)
  63. def approx_equal(x, y, tol=1e-12, rel=1e-7):
  64. """approx_equal(x, y [, tol [, rel]]) => True|False
  65. Return True if numbers x and y are approximately equal, to within some
  66. margin of error, otherwise return False. Numbers which compare equal
  67. will also compare approximately equal.
  68. x is approximately equal to y if the difference between them is less than
  69. an absolute error tol or a relative error rel, whichever is bigger.
  70. If given, both tol and rel must be finite, non-negative numbers. If not
  71. given, default values are tol=1e-12 and rel=1e-7.
  72. >>> approx_equal(1.2589, 1.2587, tol=0.0003, rel=0)
  73. True
  74. >>> approx_equal(1.2589, 1.2587, tol=0.0001, rel=0)
  75. False
  76. Absolute error is defined as abs(x-y); if that is less than or equal to
  77. tol, x and y are considered approximately equal.
  78. Relative error is defined as abs((x-y)/x) or abs((x-y)/y), whichever is
  79. smaller, provided x or y are not zero. If that figure is less than or
  80. equal to rel, x and y are considered approximately equal.
  81. Complex numbers are not directly supported. If you wish to compare to
  82. complex numbers, extract their real and imaginary parts and compare them
  83. individually.
  84. NANs always compare unequal, even with themselves. Infinities compare
  85. approximately equal if they have the same sign (both positive or both
  86. negative). Infinities with different signs compare unequal; so do
  87. comparisons of infinities with finite numbers.
  88. """
  89. if tol < 0 or rel < 0:
  90. raise ValueError('error tolerances must be non-negative')
  91. # NANs are never equal to anything, approximately or otherwise.
  92. if math.isnan(x) or math.isnan(y):
  93. return False
  94. # Numbers which compare equal also compare approximately equal.
  95. if x == y:
  96. # This includes the case of two infinities with the same sign.
  97. return True
  98. if math.isinf(x) or math.isinf(y):
  99. # This includes the case of two infinities of opposite sign, or
  100. # one infinity and one finite number.
  101. return False
  102. # Two finite numbers.
  103. actual_error = abs(x - y)
  104. allowed_error = max(tol, rel*max(abs(x), abs(y)))
  105. return actual_error <= allowed_error
  106. # This class exists only as somewhere to stick a docstring containing
  107. # doctests. The following docstring and tests were originally in a separate
  108. # module. Now that it has been merged in here, I need somewhere to hang the.
  109. # docstring. Ultimately, this class will die, and the information below will
  110. # either become redundant, or be moved into more appropriate places.
  111. class _DoNothing:
  112. """
  113. When doing numeric work, especially with floats, exact equality is often
  114. not what you want. Due to round-off error, it is often a bad idea to try
  115. to compare floats with equality. Instead the usual procedure is to test
  116. them with some (hopefully small!) allowance for error.
  117. The ``approx_equal`` function allows you to specify either an absolute
  118. error tolerance, or a relative error, or both.
  119. Absolute error tolerances are simple, but you need to know the magnitude
  120. of the quantities being compared:
  121. >>> approx_equal(12.345, 12.346, tol=1e-3)
  122. True
  123. >>> approx_equal(12.345e6, 12.346e6, tol=1e-3) # tol is too small.
  124. False
  125. Relative errors are more suitable when the values you are comparing can
  126. vary in magnitude:
  127. >>> approx_equal(12.345, 12.346, rel=1e-4)
  128. True
  129. >>> approx_equal(12.345e6, 12.346e6, rel=1e-4)
  130. True
  131. but a naive implementation of relative error testing can run into trouble
  132. around zero.
  133. If you supply both an absolute tolerance and a relative error, the
  134. comparison succeeds if either individual test succeeds:
  135. >>> approx_equal(12.345e6, 12.346e6, tol=1e-3, rel=1e-4)
  136. True
  137. """
  138. pass
  139. # We prefer this for testing numeric values that may not be exactly equal,
  140. # and avoid using TestCase.assertAlmostEqual, because it sucks :-)
  141. py_statistics = import_helper.import_fresh_module('statistics',
  142. blocked=['_statistics'])
  143. c_statistics = import_helper.import_fresh_module('statistics',
  144. fresh=['_statistics'])
  145. class TestModules(unittest.TestCase):
  146. func_names = ['_normal_dist_inv_cdf']
  147. def test_py_functions(self):
  148. for fname in self.func_names:
  149. self.assertEqual(getattr(py_statistics, fname).__module__, 'statistics')
  150. @unittest.skipUnless(c_statistics, 'requires _statistics')
  151. def test_c_functions(self):
  152. for fname in self.func_names:
  153. self.assertEqual(getattr(c_statistics, fname).__module__, '_statistics')
  154. class NumericTestCase(unittest.TestCase):
  155. """Unit test class for numeric work.
  156. This subclasses TestCase. In addition to the standard method
  157. ``TestCase.assertAlmostEqual``, ``assertApproxEqual`` is provided.
  158. """
  159. # By default, we expect exact equality, unless overridden.
  160. tol = rel = 0
  161. def assertApproxEqual(
  162. self, first, second, tol=None, rel=None, msg=None
  163. ):
  164. """Test passes if ``first`` and ``second`` are approximately equal.
  165. This test passes if ``first`` and ``second`` are equal to
  166. within ``tol``, an absolute error, or ``rel``, a relative error.
  167. If either ``tol`` or ``rel`` are None or not given, they default to
  168. test attributes of the same name (by default, 0).
  169. The objects may be either numbers, or sequences of numbers. Sequences
  170. are tested element-by-element.
  171. >>> class MyTest(NumericTestCase):
  172. ... def test_number(self):
  173. ... x = 1.0/6
  174. ... y = sum([x]*6)
  175. ... self.assertApproxEqual(y, 1.0, tol=1e-15)
  176. ... def test_sequence(self):
  177. ... a = [1.001, 1.001e-10, 1.001e10]
  178. ... b = [1.0, 1e-10, 1e10]
  179. ... self.assertApproxEqual(a, b, rel=1e-3)
  180. ...
  181. >>> import unittest
  182. >>> from io import StringIO # Suppress test runner output.
  183. >>> suite = unittest.TestLoader().loadTestsFromTestCase(MyTest)
  184. >>> unittest.TextTestRunner(stream=StringIO()).run(suite)
  185. <unittest.runner.TextTestResult run=2 errors=0 failures=0>
  186. """
  187. if tol is None:
  188. tol = self.tol
  189. if rel is None:
  190. rel = self.rel
  191. if (
  192. isinstance(first, collections.abc.Sequence) and
  193. isinstance(second, collections.abc.Sequence)
  194. ):
  195. check = self._check_approx_seq
  196. else:
  197. check = self._check_approx_num
  198. check(first, second, tol, rel, msg)
  199. def _check_approx_seq(self, first, second, tol, rel, msg):
  200. if len(first) != len(second):
  201. standardMsg = (
  202. "sequences differ in length: %d items != %d items"
  203. % (len(first), len(second))
  204. )
  205. msg = self._formatMessage(msg, standardMsg)
  206. raise self.failureException(msg)
  207. for i, (a,e) in enumerate(zip(first, second)):
  208. self._check_approx_num(a, e, tol, rel, msg, i)
  209. def _check_approx_num(self, first, second, tol, rel, msg, idx=None):
  210. if approx_equal(first, second, tol, rel):
  211. # Test passes. Return early, we are done.
  212. return None
  213. # Otherwise we failed.
  214. standardMsg = self._make_std_err_msg(first, second, tol, rel, idx)
  215. msg = self._formatMessage(msg, standardMsg)
  216. raise self.failureException(msg)
  217. @staticmethod
  218. def _make_std_err_msg(first, second, tol, rel, idx):
  219. # Create the standard error message for approx_equal failures.
  220. assert first != second
  221. template = (
  222. ' %r != %r\n'
  223. ' values differ by more than tol=%r and rel=%r\n'
  224. ' -> absolute error = %r\n'
  225. ' -> relative error = %r'
  226. )
  227. if idx is not None:
  228. header = 'numeric sequences first differ at index %d.\n' % idx
  229. template = header + template
  230. # Calculate actual errors:
  231. abs_err, rel_err = _calc_errors(first, second)
  232. return template % (first, second, tol, rel, abs_err, rel_err)
  233. # ========================
  234. # === Test the helpers ===
  235. # ========================
  236. class TestSign(unittest.TestCase):
  237. """Test that the helper function sign() works correctly."""
  238. def testZeroes(self):
  239. # Test that signed zeroes report their sign correctly.
  240. self.assertEqual(sign(0.0), +1)
  241. self.assertEqual(sign(-0.0), -1)
  242. # --- Tests for approx_equal ---
  243. class ApproxEqualSymmetryTest(unittest.TestCase):
  244. # Test symmetry of approx_equal.
  245. def test_relative_symmetry(self):
  246. # Check that approx_equal treats relative error symmetrically.
  247. # (a-b)/a is usually not equal to (a-b)/b. Ensure that this
  248. # doesn't matter.
  249. #
  250. # Note: the reason for this test is that an early version
  251. # of approx_equal was not symmetric. A relative error test
  252. # would pass, or fail, depending on which value was passed
  253. # as the first argument.
  254. #
  255. args1 = [2456, 37.8, -12.45, Decimal('2.54'), Fraction(17, 54)]
  256. args2 = [2459, 37.2, -12.41, Decimal('2.59'), Fraction(15, 54)]
  257. assert len(args1) == len(args2)
  258. for a, b in zip(args1, args2):
  259. self.do_relative_symmetry(a, b)
  260. def do_relative_symmetry(self, a, b):
  261. a, b = min(a, b), max(a, b)
  262. assert a < b
  263. delta = b - a # The absolute difference between the values.
  264. rel_err1, rel_err2 = abs(delta/a), abs(delta/b)
  265. # Choose an error margin halfway between the two.
  266. rel = (rel_err1 + rel_err2)/2
  267. # Now see that values a and b compare approx equal regardless of
  268. # which is given first.
  269. self.assertTrue(approx_equal(a, b, tol=0, rel=rel))
  270. self.assertTrue(approx_equal(b, a, tol=0, rel=rel))
  271. def test_symmetry(self):
  272. # Test that approx_equal(a, b) == approx_equal(b, a)
  273. args = [-23, -2, 5, 107, 93568]
  274. delta = 2
  275. for a in args:
  276. for type_ in (int, float, Decimal, Fraction):
  277. x = type_(a)*100
  278. y = x + delta
  279. r = abs(delta/max(x, y))
  280. # There are five cases to check:
  281. # 1) actual error <= tol, <= rel
  282. self.do_symmetry_test(x, y, tol=delta, rel=r)
  283. self.do_symmetry_test(x, y, tol=delta+1, rel=2*r)
  284. # 2) actual error > tol, > rel
  285. self.do_symmetry_test(x, y, tol=delta-1, rel=r/2)
  286. # 3) actual error <= tol, > rel
  287. self.do_symmetry_test(x, y, tol=delta, rel=r/2)
  288. # 4) actual error > tol, <= rel
  289. self.do_symmetry_test(x, y, tol=delta-1, rel=r)
  290. self.do_symmetry_test(x, y, tol=delta-1, rel=2*r)
  291. # 5) exact equality test
  292. self.do_symmetry_test(x, x, tol=0, rel=0)
  293. self.do_symmetry_test(x, y, tol=0, rel=0)
  294. def do_symmetry_test(self, a, b, tol, rel):
  295. template = "approx_equal comparisons don't match for %r"
  296. flag1 = approx_equal(a, b, tol, rel)
  297. flag2 = approx_equal(b, a, tol, rel)
  298. self.assertEqual(flag1, flag2, template.format((a, b, tol, rel)))
  299. class ApproxEqualExactTest(unittest.TestCase):
  300. # Test the approx_equal function with exactly equal values.
  301. # Equal values should compare as approximately equal.
  302. # Test cases for exactly equal values, which should compare approx
  303. # equal regardless of the error tolerances given.
  304. def do_exactly_equal_test(self, x, tol, rel):
  305. result = approx_equal(x, x, tol=tol, rel=rel)
  306. self.assertTrue(result, 'equality failure for x=%r' % x)
  307. result = approx_equal(-x, -x, tol=tol, rel=rel)
  308. self.assertTrue(result, 'equality failure for x=%r' % -x)
  309. def test_exactly_equal_ints(self):
  310. # Test that equal int values are exactly equal.
  311. for n in [42, 19740, 14974, 230, 1795, 700245, 36587]:
  312. self.do_exactly_equal_test(n, 0, 0)
  313. def test_exactly_equal_floats(self):
  314. # Test that equal float values are exactly equal.
  315. for x in [0.42, 1.9740, 1497.4, 23.0, 179.5, 70.0245, 36.587]:
  316. self.do_exactly_equal_test(x, 0, 0)
  317. def test_exactly_equal_fractions(self):
  318. # Test that equal Fraction values are exactly equal.
  319. F = Fraction
  320. for f in [F(1, 2), F(0), F(5, 3), F(9, 7), F(35, 36), F(3, 7)]:
  321. self.do_exactly_equal_test(f, 0, 0)
  322. def test_exactly_equal_decimals(self):
  323. # Test that equal Decimal values are exactly equal.
  324. D = Decimal
  325. for d in map(D, "8.2 31.274 912.04 16.745 1.2047".split()):
  326. self.do_exactly_equal_test(d, 0, 0)
  327. def test_exactly_equal_absolute(self):
  328. # Test that equal values are exactly equal with an absolute error.
  329. for n in [16, 1013, 1372, 1198, 971, 4]:
  330. # Test as ints.
  331. self.do_exactly_equal_test(n, 0.01, 0)
  332. # Test as floats.
  333. self.do_exactly_equal_test(n/10, 0.01, 0)
  334. # Test as Fractions.
  335. f = Fraction(n, 1234)
  336. self.do_exactly_equal_test(f, 0.01, 0)
  337. def test_exactly_equal_absolute_decimals(self):
  338. # Test equal Decimal values are exactly equal with an absolute error.
  339. self.do_exactly_equal_test(Decimal("3.571"), Decimal("0.01"), 0)
  340. self.do_exactly_equal_test(-Decimal("81.3971"), Decimal("0.01"), 0)
  341. def test_exactly_equal_relative(self):
  342. # Test that equal values are exactly equal with a relative error.
  343. for x in [8347, 101.3, -7910.28, Fraction(5, 21)]:
  344. self.do_exactly_equal_test(x, 0, 0.01)
  345. self.do_exactly_equal_test(Decimal("11.68"), 0, Decimal("0.01"))
  346. def test_exactly_equal_both(self):
  347. # Test that equal values are equal when both tol and rel are given.
  348. for x in [41017, 16.742, -813.02, Fraction(3, 8)]:
  349. self.do_exactly_equal_test(x, 0.1, 0.01)
  350. D = Decimal
  351. self.do_exactly_equal_test(D("7.2"), D("0.1"), D("0.01"))
  352. class ApproxEqualUnequalTest(unittest.TestCase):
  353. # Unequal values should compare unequal with zero error tolerances.
  354. # Test cases for unequal values, with exact equality test.
  355. def do_exactly_unequal_test(self, x):
  356. for a in (x, -x):
  357. result = approx_equal(a, a+1, tol=0, rel=0)
  358. self.assertFalse(result, 'inequality failure for x=%r' % a)
  359. def test_exactly_unequal_ints(self):
  360. # Test unequal int values are unequal with zero error tolerance.
  361. for n in [951, 572305, 478, 917, 17240]:
  362. self.do_exactly_unequal_test(n)
  363. def test_exactly_unequal_floats(self):
  364. # Test unequal float values are unequal with zero error tolerance.
  365. for x in [9.51, 5723.05, 47.8, 9.17, 17.24]:
  366. self.do_exactly_unequal_test(x)
  367. def test_exactly_unequal_fractions(self):
  368. # Test that unequal Fractions are unequal with zero error tolerance.
  369. F = Fraction
  370. for f in [F(1, 5), F(7, 9), F(12, 11), F(101, 99023)]:
  371. self.do_exactly_unequal_test(f)
  372. def test_exactly_unequal_decimals(self):
  373. # Test that unequal Decimals are unequal with zero error tolerance.
  374. for d in map(Decimal, "3.1415 298.12 3.47 18.996 0.00245".split()):
  375. self.do_exactly_unequal_test(d)
  376. class ApproxEqualInexactTest(unittest.TestCase):
  377. # Inexact test cases for approx_error.
  378. # Test cases when comparing two values that are not exactly equal.
  379. # === Absolute error tests ===
  380. def do_approx_equal_abs_test(self, x, delta):
  381. template = "Test failure for x={!r}, y={!r}"
  382. for y in (x + delta, x - delta):
  383. msg = template.format(x, y)
  384. self.assertTrue(approx_equal(x, y, tol=2*delta, rel=0), msg)
  385. self.assertFalse(approx_equal(x, y, tol=delta/2, rel=0), msg)
  386. def test_approx_equal_absolute_ints(self):
  387. # Test approximate equality of ints with an absolute error.
  388. for n in [-10737, -1975, -7, -2, 0, 1, 9, 37, 423, 9874, 23789110]:
  389. self.do_approx_equal_abs_test(n, 10)
  390. self.do_approx_equal_abs_test(n, 2)
  391. def test_approx_equal_absolute_floats(self):
  392. # Test approximate equality of floats with an absolute error.
  393. for x in [-284.126, -97.1, -3.4, -2.15, 0.5, 1.0, 7.8, 4.23, 3817.4]:
  394. self.do_approx_equal_abs_test(x, 1.5)
  395. self.do_approx_equal_abs_test(x, 0.01)
  396. self.do_approx_equal_abs_test(x, 0.0001)
  397. def test_approx_equal_absolute_fractions(self):
  398. # Test approximate equality of Fractions with an absolute error.
  399. delta = Fraction(1, 29)
  400. numerators = [-84, -15, -2, -1, 0, 1, 5, 17, 23, 34, 71]
  401. for f in (Fraction(n, 29) for n in numerators):
  402. self.do_approx_equal_abs_test(f, delta)
  403. self.do_approx_equal_abs_test(f, float(delta))
  404. def test_approx_equal_absolute_decimals(self):
  405. # Test approximate equality of Decimals with an absolute error.
  406. delta = Decimal("0.01")
  407. for d in map(Decimal, "1.0 3.5 36.08 61.79 7912.3648".split()):
  408. self.do_approx_equal_abs_test(d, delta)
  409. self.do_approx_equal_abs_test(-d, delta)
  410. def test_cross_zero(self):
  411. # Test for the case of the two values having opposite signs.
  412. self.assertTrue(approx_equal(1e-5, -1e-5, tol=1e-4, rel=0))
  413. # === Relative error tests ===
  414. def do_approx_equal_rel_test(self, x, delta):
  415. template = "Test failure for x={!r}, y={!r}"
  416. for y in (x*(1+delta), x*(1-delta)):
  417. msg = template.format(x, y)
  418. self.assertTrue(approx_equal(x, y, tol=0, rel=2*delta), msg)
  419. self.assertFalse(approx_equal(x, y, tol=0, rel=delta/2), msg)
  420. def test_approx_equal_relative_ints(self):
  421. # Test approximate equality of ints with a relative error.
  422. self.assertTrue(approx_equal(64, 47, tol=0, rel=0.36))
  423. self.assertTrue(approx_equal(64, 47, tol=0, rel=0.37))
  424. # ---
  425. self.assertTrue(approx_equal(449, 512, tol=0, rel=0.125))
  426. self.assertTrue(approx_equal(448, 512, tol=0, rel=0.125))
  427. self.assertFalse(approx_equal(447, 512, tol=0, rel=0.125))
  428. def test_approx_equal_relative_floats(self):
  429. # Test approximate equality of floats with a relative error.
  430. for x in [-178.34, -0.1, 0.1, 1.0, 36.97, 2847.136, 9145.074]:
  431. self.do_approx_equal_rel_test(x, 0.02)
  432. self.do_approx_equal_rel_test(x, 0.0001)
  433. def test_approx_equal_relative_fractions(self):
  434. # Test approximate equality of Fractions with a relative error.
  435. F = Fraction
  436. delta = Fraction(3, 8)
  437. for f in [F(3, 84), F(17, 30), F(49, 50), F(92, 85)]:
  438. for d in (delta, float(delta)):
  439. self.do_approx_equal_rel_test(f, d)
  440. self.do_approx_equal_rel_test(-f, d)
  441. def test_approx_equal_relative_decimals(self):
  442. # Test approximate equality of Decimals with a relative error.
  443. for d in map(Decimal, "0.02 1.0 5.7 13.67 94.138 91027.9321".split()):
  444. self.do_approx_equal_rel_test(d, Decimal("0.001"))
  445. self.do_approx_equal_rel_test(-d, Decimal("0.05"))
  446. # === Both absolute and relative error tests ===
  447. # There are four cases to consider:
  448. # 1) actual error <= both absolute and relative error
  449. # 2) actual error <= absolute error but > relative error
  450. # 3) actual error <= relative error but > absolute error
  451. # 4) actual error > both absolute and relative error
  452. def do_check_both(self, a, b, tol, rel, tol_flag, rel_flag):
  453. check = self.assertTrue if tol_flag else self.assertFalse
  454. check(approx_equal(a, b, tol=tol, rel=0))
  455. check = self.assertTrue if rel_flag else self.assertFalse
  456. check(approx_equal(a, b, tol=0, rel=rel))
  457. check = self.assertTrue if (tol_flag or rel_flag) else self.assertFalse
  458. check(approx_equal(a, b, tol=tol, rel=rel))
  459. def test_approx_equal_both1(self):
  460. # Test actual error <= both absolute and relative error.
  461. self.do_check_both(7.955, 7.952, 0.004, 3.8e-4, True, True)
  462. self.do_check_both(-7.387, -7.386, 0.002, 0.0002, True, True)
  463. def test_approx_equal_both2(self):
  464. # Test actual error <= absolute error but > relative error.
  465. self.do_check_both(7.955, 7.952, 0.004, 3.7e-4, True, False)
  466. def test_approx_equal_both3(self):
  467. # Test actual error <= relative error but > absolute error.
  468. self.do_check_both(7.955, 7.952, 0.001, 3.8e-4, False, True)
  469. def test_approx_equal_both4(self):
  470. # Test actual error > both absolute and relative error.
  471. self.do_check_both(2.78, 2.75, 0.01, 0.001, False, False)
  472. self.do_check_both(971.44, 971.47, 0.02, 3e-5, False, False)
  473. class ApproxEqualSpecialsTest(unittest.TestCase):
  474. # Test approx_equal with NANs and INFs and zeroes.
  475. def test_inf(self):
  476. for type_ in (float, Decimal):
  477. inf = type_('inf')
  478. self.assertTrue(approx_equal(inf, inf))
  479. self.assertTrue(approx_equal(inf, inf, 0, 0))
  480. self.assertTrue(approx_equal(inf, inf, 1, 0.01))
  481. self.assertTrue(approx_equal(-inf, -inf))
  482. self.assertFalse(approx_equal(inf, -inf))
  483. self.assertFalse(approx_equal(inf, 1000))
  484. def test_nan(self):
  485. for type_ in (float, Decimal):
  486. nan = type_('nan')
  487. for other in (nan, type_('inf'), 1000):
  488. self.assertFalse(approx_equal(nan, other))
  489. def test_float_zeroes(self):
  490. nzero = math.copysign(0.0, -1)
  491. self.assertTrue(approx_equal(nzero, 0.0, tol=0.1, rel=0.1))
  492. def test_decimal_zeroes(self):
  493. nzero = Decimal("-0.0")
  494. self.assertTrue(approx_equal(nzero, Decimal(0), tol=0.1, rel=0.1))
  495. class TestApproxEqualErrors(unittest.TestCase):
  496. # Test error conditions of approx_equal.
  497. def test_bad_tol(self):
  498. # Test negative tol raises.
  499. self.assertRaises(ValueError, approx_equal, 100, 100, -1, 0.1)
  500. def test_bad_rel(self):
  501. # Test negative rel raises.
  502. self.assertRaises(ValueError, approx_equal, 100, 100, 1, -0.1)
  503. # --- Tests for NumericTestCase ---
  504. # The formatting routine that generates the error messages is complex enough
  505. # that it too needs testing.
  506. class TestNumericTestCase(unittest.TestCase):
  507. # The exact wording of NumericTestCase error messages is *not* guaranteed,
  508. # but we need to give them some sort of test to ensure that they are
  509. # generated correctly. As a compromise, we look for specific substrings
  510. # that are expected to be found even if the overall error message changes.
  511. def do_test(self, args):
  512. actual_msg = NumericTestCase._make_std_err_msg(*args)
  513. expected = self.generate_substrings(*args)
  514. for substring in expected:
  515. self.assertIn(substring, actual_msg)
  516. def test_numerictestcase_is_testcase(self):
  517. # Ensure that NumericTestCase actually is a TestCase.
  518. self.assertTrue(issubclass(NumericTestCase, unittest.TestCase))
  519. def test_error_msg_numeric(self):
  520. # Test the error message generated for numeric comparisons.
  521. args = (2.5, 4.0, 0.5, 0.25, None)
  522. self.do_test(args)
  523. def test_error_msg_sequence(self):
  524. # Test the error message generated for sequence comparisons.
  525. args = (3.75, 8.25, 1.25, 0.5, 7)
  526. self.do_test(args)
  527. def generate_substrings(self, first, second, tol, rel, idx):
  528. """Return substrings we expect to see in error messages."""
  529. abs_err, rel_err = _calc_errors(first, second)
  530. substrings = [
  531. 'tol=%r' % tol,
  532. 'rel=%r' % rel,
  533. 'absolute error = %r' % abs_err,
  534. 'relative error = %r' % rel_err,
  535. ]
  536. if idx is not None:
  537. substrings.append('differ at index %d' % idx)
  538. return substrings
  539. # =======================================
  540. # === Tests for the statistics module ===
  541. # =======================================
  542. class GlobalsTest(unittest.TestCase):
  543. module = statistics
  544. expected_metadata = ["__doc__", "__all__"]
  545. def test_meta(self):
  546. # Test for the existence of metadata.
  547. for meta in self.expected_metadata:
  548. self.assertTrue(hasattr(self.module, meta),
  549. "%s not present" % meta)
  550. def test_check_all(self):
  551. # Check everything in __all__ exists and is public.
  552. module = self.module
  553. for name in module.__all__:
  554. # No private names in __all__:
  555. self.assertFalse(name.startswith("_"),
  556. 'private name "%s" in __all__' % name)
  557. # And anything in __all__ must exist:
  558. self.assertTrue(hasattr(module, name),
  559. 'missing name "%s" in __all__' % name)
  560. class DocTests(unittest.TestCase):
  561. @unittest.skipIf(sys.flags.optimize >= 2,
  562. "Docstrings are omitted with -OO and above")
  563. def test_doc_tests(self):
  564. failed, tried = doctest.testmod(statistics, optionflags=doctest.ELLIPSIS)
  565. self.assertGreater(tried, 0)
  566. self.assertEqual(failed, 0)
  567. class StatisticsErrorTest(unittest.TestCase):
  568. def test_has_exception(self):
  569. errmsg = (
  570. "Expected StatisticsError to be a ValueError, but got a"
  571. " subclass of %r instead."
  572. )
  573. self.assertTrue(hasattr(statistics, 'StatisticsError'))
  574. self.assertTrue(
  575. issubclass(statistics.StatisticsError, ValueError),
  576. errmsg % statistics.StatisticsError.__base__
  577. )
  578. # === Tests for private utility functions ===
  579. class ExactRatioTest(unittest.TestCase):
  580. # Test _exact_ratio utility.
  581. def test_int(self):
  582. for i in (-20, -3, 0, 5, 99, 10**20):
  583. self.assertEqual(statistics._exact_ratio(i), (i, 1))
  584. def test_fraction(self):
  585. numerators = (-5, 1, 12, 38)
  586. for n in numerators:
  587. f = Fraction(n, 37)
  588. self.assertEqual(statistics._exact_ratio(f), (n, 37))
  589. def test_float(self):
  590. self.assertEqual(statistics._exact_ratio(0.125), (1, 8))
  591. self.assertEqual(statistics._exact_ratio(1.125), (9, 8))
  592. data = [random.uniform(-100, 100) for _ in range(100)]
  593. for x in data:
  594. num, den = statistics._exact_ratio(x)
  595. self.assertEqual(x, num/den)
  596. def test_decimal(self):
  597. D = Decimal
  598. _exact_ratio = statistics._exact_ratio
  599. self.assertEqual(_exact_ratio(D("0.125")), (1, 8))
  600. self.assertEqual(_exact_ratio(D("12.345")), (2469, 200))
  601. self.assertEqual(_exact_ratio(D("-1.98")), (-99, 50))
  602. def test_inf(self):
  603. INF = float("INF")
  604. class MyFloat(float):
  605. pass
  606. class MyDecimal(Decimal):
  607. pass
  608. for inf in (INF, -INF):
  609. for type_ in (float, MyFloat, Decimal, MyDecimal):
  610. x = type_(inf)
  611. ratio = statistics._exact_ratio(x)
  612. self.assertEqual(ratio, (x, None))
  613. self.assertEqual(type(ratio[0]), type_)
  614. self.assertTrue(math.isinf(ratio[0]))
  615. def test_float_nan(self):
  616. NAN = float("NAN")
  617. class MyFloat(float):
  618. pass
  619. for nan in (NAN, MyFloat(NAN)):
  620. ratio = statistics._exact_ratio(nan)
  621. self.assertTrue(math.isnan(ratio[0]))
  622. self.assertIs(ratio[1], None)
  623. self.assertEqual(type(ratio[0]), type(nan))
  624. def test_decimal_nan(self):
  625. NAN = Decimal("NAN")
  626. sNAN = Decimal("sNAN")
  627. class MyDecimal(Decimal):
  628. pass
  629. for nan in (NAN, MyDecimal(NAN), sNAN, MyDecimal(sNAN)):
  630. ratio = statistics._exact_ratio(nan)
  631. self.assertTrue(_nan_equal(ratio[0], nan))
  632. self.assertIs(ratio[1], None)
  633. self.assertEqual(type(ratio[0]), type(nan))
  634. class DecimalToRatioTest(unittest.TestCase):
  635. # Test _exact_ratio private function.
  636. def test_infinity(self):
  637. # Test that INFs are handled correctly.
  638. inf = Decimal('INF')
  639. self.assertEqual(statistics._exact_ratio(inf), (inf, None))
  640. self.assertEqual(statistics._exact_ratio(-inf), (-inf, None))
  641. def test_nan(self):
  642. # Test that NANs are handled correctly.
  643. for nan in (Decimal('NAN'), Decimal('sNAN')):
  644. num, den = statistics._exact_ratio(nan)
  645. # Because NANs always compare non-equal, we cannot use assertEqual.
  646. # Nor can we use an identity test, as we don't guarantee anything
  647. # about the object identity.
  648. self.assertTrue(_nan_equal(num, nan))
  649. self.assertIs(den, None)
  650. def test_sign(self):
  651. # Test sign is calculated correctly.
  652. numbers = [Decimal("9.8765e12"), Decimal("9.8765e-12")]
  653. for d in numbers:
  654. # First test positive decimals.
  655. assert d > 0
  656. num, den = statistics._exact_ratio(d)
  657. self.assertGreaterEqual(num, 0)
  658. self.assertGreater(den, 0)
  659. # Then test negative decimals.
  660. num, den = statistics._exact_ratio(-d)
  661. self.assertLessEqual(num, 0)
  662. self.assertGreater(den, 0)
  663. def test_negative_exponent(self):
  664. # Test result when the exponent is negative.
  665. t = statistics._exact_ratio(Decimal("0.1234"))
  666. self.assertEqual(t, (617, 5000))
  667. def test_positive_exponent(self):
  668. # Test results when the exponent is positive.
  669. t = statistics._exact_ratio(Decimal("1.234e7"))
  670. self.assertEqual(t, (12340000, 1))
  671. def test_regression_20536(self):
  672. # Regression test for issue 20536.
  673. # See http://bugs.python.org/issue20536
  674. t = statistics._exact_ratio(Decimal("1e2"))
  675. self.assertEqual(t, (100, 1))
  676. t = statistics._exact_ratio(Decimal("1.47e5"))
  677. self.assertEqual(t, (147000, 1))
  678. class IsFiniteTest(unittest.TestCase):
  679. # Test _isfinite private function.
  680. def test_finite(self):
  681. # Test that finite numbers are recognised as finite.
  682. for x in (5, Fraction(1, 3), 2.5, Decimal("5.5")):
  683. self.assertTrue(statistics._isfinite(x))
  684. def test_infinity(self):
  685. # Test that INFs are not recognised as finite.
  686. for x in (float("inf"), Decimal("inf")):
  687. self.assertFalse(statistics._isfinite(x))
  688. def test_nan(self):
  689. # Test that NANs are not recognised as finite.
  690. for x in (float("nan"), Decimal("NAN"), Decimal("sNAN")):
  691. self.assertFalse(statistics._isfinite(x))
  692. class CoerceTest(unittest.TestCase):
  693. # Test that private function _coerce correctly deals with types.
  694. # The coercion rules are currently an implementation detail, although at
  695. # some point that should change. The tests and comments here define the
  696. # correct implementation.
  697. # Pre-conditions of _coerce:
  698. #
  699. # - The first time _sum calls _coerce, the
  700. # - coerce(T, S) will never be called with bool as the first argument;
  701. # this is a pre-condition, guarded with an assertion.
  702. #
  703. # - coerce(T, T) will always return T; we assume T is a valid numeric
  704. # type. Violate this assumption at your own risk.
  705. #
  706. # - Apart from as above, bool is treated as if it were actually int.
  707. #
  708. # - coerce(int, X) and coerce(X, int) return X.
  709. # -
  710. def test_bool(self):
  711. # bool is somewhat special, due to the pre-condition that it is
  712. # never given as the first argument to _coerce, and that it cannot
  713. # be subclassed. So we test it specially.
  714. for T in (int, float, Fraction, Decimal):
  715. self.assertIs(statistics._coerce(T, bool), T)
  716. class MyClass(T): pass
  717. self.assertIs(statistics._coerce(MyClass, bool), MyClass)
  718. def assertCoerceTo(self, A, B):
  719. """Assert that type A coerces to B."""
  720. self.assertIs(statistics._coerce(A, B), B)
  721. self.assertIs(statistics._coerce(B, A), B)
  722. def check_coerce_to(self, A, B):
  723. """Checks that type A coerces to B, including subclasses."""
  724. # Assert that type A is coerced to B.
  725. self.assertCoerceTo(A, B)
  726. # Subclasses of A are also coerced to B.
  727. class SubclassOfA(A): pass
  728. self.assertCoerceTo(SubclassOfA, B)
  729. # A, and subclasses of A, are coerced to subclasses of B.
  730. class SubclassOfB(B): pass
  731. self.assertCoerceTo(A, SubclassOfB)
  732. self.assertCoerceTo(SubclassOfA, SubclassOfB)
  733. def assertCoerceRaises(self, A, B):
  734. """Assert that coercing A to B, or vice versa, raises TypeError."""
  735. self.assertRaises(TypeError, statistics._coerce, (A, B))
  736. self.assertRaises(TypeError, statistics._coerce, (B, A))
  737. def check_type_coercions(self, T):
  738. """Check that type T coerces correctly with subclasses of itself."""
  739. assert T is not bool
  740. # Coercing a type with itself returns the same type.
  741. self.assertIs(statistics._coerce(T, T), T)
  742. # Coercing a type with a subclass of itself returns the subclass.
  743. class U(T): pass
  744. class V(T): pass
  745. class W(U): pass
  746. for typ in (U, V, W):
  747. self.assertCoerceTo(T, typ)
  748. self.assertCoerceTo(U, W)
  749. # Coercing two subclasses that aren't parent/child is an error.
  750. self.assertCoerceRaises(U, V)
  751. self.assertCoerceRaises(V, W)
  752. def test_int(self):
  753. # Check that int coerces correctly.
  754. self.check_type_coercions(int)
  755. for typ in (float, Fraction, Decimal):
  756. self.check_coerce_to(int, typ)
  757. def test_fraction(self):
  758. # Check that Fraction coerces correctly.
  759. self.check_type_coercions(Fraction)
  760. self.check_coerce_to(Fraction, float)
  761. def test_decimal(self):
  762. # Check that Decimal coerces correctly.
  763. self.check_type_coercions(Decimal)
  764. def test_float(self):
  765. # Check that float coerces correctly.
  766. self.check_type_coercions(float)
  767. def test_non_numeric_types(self):
  768. for bad_type in (str, list, type(None), tuple, dict):
  769. for good_type in (int, float, Fraction, Decimal):
  770. self.assertCoerceRaises(good_type, bad_type)
  771. def test_incompatible_types(self):
  772. # Test that incompatible types raise.
  773. for T in (float, Fraction):
  774. class MySubclass(T): pass
  775. self.assertCoerceRaises(T, Decimal)
  776. self.assertCoerceRaises(MySubclass, Decimal)
  777. class ConvertTest(unittest.TestCase):
  778. # Test private _convert function.
  779. def check_exact_equal(self, x, y):
  780. """Check that x equals y, and has the same type as well."""
  781. self.assertEqual(x, y)
  782. self.assertIs(type(x), type(y))
  783. def test_int(self):
  784. # Test conversions to int.
  785. x = statistics._convert(Fraction(71), int)
  786. self.check_exact_equal(x, 71)
  787. class MyInt(int): pass
  788. x = statistics._convert(Fraction(17), MyInt)
  789. self.check_exact_equal(x, MyInt(17))
  790. def test_fraction(self):
  791. # Test conversions to Fraction.
  792. x = statistics._convert(Fraction(95, 99), Fraction)
  793. self.check_exact_equal(x, Fraction(95, 99))
  794. class MyFraction(Fraction):
  795. def __truediv__(self, other):
  796. return self.__class__(super().__truediv__(other))
  797. x = statistics._convert(Fraction(71, 13), MyFraction)
  798. self.check_exact_equal(x, MyFraction(71, 13))
  799. def test_float(self):
  800. # Test conversions to float.
  801. x = statistics._convert(Fraction(-1, 2), float)
  802. self.check_exact_equal(x, -0.5)
  803. class MyFloat(float):
  804. def __truediv__(self, other):
  805. return self.__class__(super().__truediv__(other))
  806. x = statistics._convert(Fraction(9, 8), MyFloat)
  807. self.check_exact_equal(x, MyFloat(1.125))
  808. def test_decimal(self):
  809. # Test conversions to Decimal.
  810. x = statistics._convert(Fraction(1, 40), Decimal)
  811. self.check_exact_equal(x, Decimal("0.025"))
  812. class MyDecimal(Decimal):
  813. def __truediv__(self, other):
  814. return self.__class__(super().__truediv__(other))
  815. x = statistics._convert(Fraction(-15, 16), MyDecimal)
  816. self.check_exact_equal(x, MyDecimal("-0.9375"))
  817. def test_inf(self):
  818. for INF in (float('inf'), Decimal('inf')):
  819. for inf in (INF, -INF):
  820. x = statistics._convert(inf, type(inf))
  821. self.check_exact_equal(x, inf)
  822. def test_nan(self):
  823. for nan in (float('nan'), Decimal('NAN'), Decimal('sNAN')):
  824. x = statistics._convert(nan, type(nan))
  825. self.assertTrue(_nan_equal(x, nan))
  826. def test_invalid_input_type(self):
  827. with self.assertRaises(TypeError):
  828. statistics._convert(None, float)
  829. class FailNegTest(unittest.TestCase):
  830. """Test _fail_neg private function."""
  831. def test_pass_through(self):
  832. # Test that values are passed through unchanged.
  833. values = [1, 2.0, Fraction(3), Decimal(4)]
  834. new = list(statistics._fail_neg(values))
  835. self.assertEqual(values, new)
  836. def test_negatives_raise(self):
  837. # Test that negatives raise an exception.
  838. for x in [1, 2.0, Fraction(3), Decimal(4)]:
  839. seq = [-x]
  840. it = statistics._fail_neg(seq)
  841. self.assertRaises(statistics.StatisticsError, next, it)
  842. def test_error_msg(self):
  843. # Test that a given error message is used.
  844. msg = "badness #%d" % random.randint(10000, 99999)
  845. try:
  846. next(statistics._fail_neg([-1], msg))
  847. except statistics.StatisticsError as e:
  848. errmsg = e.args[0]
  849. else:
  850. self.fail("expected exception, but it didn't happen")
  851. self.assertEqual(errmsg, msg)
  852. # === Tests for public functions ===
  853. class UnivariateCommonMixin:
  854. # Common tests for most univariate functions that take a data argument.
  855. def test_no_args(self):
  856. # Fail if given no arguments.
  857. self.assertRaises(TypeError, self.func)
  858. def test_empty_data(self):
  859. # Fail when the data argument (first argument) is empty.
  860. for empty in ([], (), iter([])):
  861. self.assertRaises(statistics.StatisticsError, self.func, empty)
  862. def prepare_data(self):
  863. """Return int data for various tests."""
  864. data = list(range(10))
  865. while data == sorted(data):
  866. random.shuffle(data)
  867. return data
  868. def test_no_inplace_modifications(self):
  869. # Test that the function does not modify its input data.
  870. data = self.prepare_data()
  871. assert len(data) != 1 # Necessary to avoid infinite loop.
  872. assert data != sorted(data)
  873. saved = data[:]
  874. assert data is not saved
  875. _ = self.func(data)
  876. self.assertListEqual(data, saved, "data has been modified")
  877. def test_order_doesnt_matter(self):
  878. # Test that the order of data points doesn't change the result.
  879. # CAUTION: due to floating point rounding errors, the result actually
  880. # may depend on the order. Consider this test representing an ideal.
  881. # To avoid this test failing, only test with exact values such as ints
  882. # or Fractions.
  883. data = [1, 2, 3, 3, 3, 4, 5, 6]*100
  884. expected = self.func(data)
  885. random.shuffle(data)
  886. actual = self.func(data)
  887. self.assertEqual(expected, actual)
  888. def test_type_of_data_collection(self):
  889. # Test that the type of iterable data doesn't effect the result.
  890. class MyList(list):
  891. pass
  892. class MyTuple(tuple):
  893. pass
  894. def generator(data):
  895. return (obj for obj in data)
  896. data = self.prepare_data()
  897. expected = self.func(data)
  898. for kind in (list, tuple, iter, MyList, MyTuple, generator):
  899. result = self.func(kind(data))
  900. self.assertEqual(result, expected)
  901. def test_range_data(self):
  902. # Test that functions work with range objects.
  903. data = range(20, 50, 3)
  904. expected = self.func(list(data))
  905. self.assertEqual(self.func(data), expected)
  906. def test_bad_arg_types(self):
  907. # Test that function raises when given data of the wrong type.
  908. # Don't roll the following into a loop like this:
  909. # for bad in list_of_bad:
  910. # self.check_for_type_error(bad)
  911. #
  912. # Since assertRaises doesn't show the arguments that caused the test
  913. # failure, it is very difficult to debug these test failures when the
  914. # following are in a loop.
  915. self.check_for_type_error(None)
  916. self.check_for_type_error(23)
  917. self.check_for_type_error(42.0)
  918. self.check_for_type_error(object())
  919. def check_for_type_error(self, *args):
  920. self.assertRaises(TypeError, self.func, *args)
  921. def test_type_of_data_element(self):
  922. # Check the type of data elements doesn't affect the numeric result.
  923. # This is a weaker test than UnivariateTypeMixin.testTypesConserved,
  924. # because it checks the numeric result by equality, but not by type.
  925. class MyFloat(float):
  926. def __truediv__(self, other):
  927. return type(self)(super().__truediv__(other))
  928. def __add__(self, other):
  929. return type(self)(super().__add__(other))
  930. __radd__ = __add__
  931. raw = self.prepare_data()
  932. expected = self.func(raw)
  933. for kind in (float, MyFloat, Decimal, Fraction):
  934. data = [kind(x) for x in raw]
  935. result = type(expected)(self.func(data))
  936. self.assertEqual(result, expected)
  937. class UnivariateTypeMixin:
  938. """Mixin class for type-conserving functions.
  939. This mixin class holds test(s) for functions which conserve the type of
  940. individual data points. E.g. the mean of a list of Fractions should itself
  941. be a Fraction.
  942. Not all tests to do with types need go in this class. Only those that
  943. rely on the function returning the same type as its input data.
  944. """
  945. def prepare_types_for_conservation_test(self):
  946. """Return the types which are expected to be conserved."""
  947. class MyFloat(float):
  948. def __truediv__(self, other):
  949. return type(self)(super().__truediv__(other))
  950. def __rtruediv__(self, other):
  951. return type(self)(super().__rtruediv__(other))
  952. def __sub__(self, other):
  953. return type(self)(super().__sub__(other))
  954. def __rsub__(self, other):
  955. return type(self)(super().__rsub__(other))
  956. def __pow__(self, other):
  957. return type(self)(super().__pow__(other))
  958. def __add__(self, other):
  959. return type(self)(super().__add__(other))
  960. __radd__ = __add__
  961. def __mul__(self, other):
  962. return type(self)(super().__mul__(other))
  963. __rmul__ = __mul__
  964. return (float, Decimal, Fraction, MyFloat)
  965. def test_types_conserved(self):
  966. # Test that functions keeps the same type as their data points.
  967. # (Excludes mixed data types.) This only tests the type of the return
  968. # result, not the value.
  969. data = self.prepare_data()
  970. for kind in self.prepare_types_for_conservation_test():
  971. d = [kind(x) for x in data]
  972. result = self.func(d)
  973. self.assertIs(type(result), kind)
  974. class TestSumCommon(UnivariateCommonMixin, UnivariateTypeMixin):
  975. # Common test cases for statistics._sum() function.
  976. # This test suite looks only at the numeric value returned by _sum,
  977. # after conversion to the appropriate type.
  978. def setUp(self):
  979. def simplified_sum(*args):
  980. T, value, n = statistics._sum(*args)
  981. return statistics._coerce(value, T)
  982. self.func = simplified_sum
  983. class TestSum(NumericTestCase):
  984. # Test cases for statistics._sum() function.
  985. # These tests look at the entire three value tuple returned by _sum.
  986. def setUp(self):
  987. self.func = statistics._sum
  988. def test_empty_data(self):
  989. # Override test for empty data.
  990. for data in ([], (), iter([])):
  991. self.assertEqual(self.func(data), (int, Fraction(0), 0))
  992. def test_ints(self):
  993. self.assertEqual(self.func([1, 5, 3, -4, -8, 20, 42, 1]),
  994. (int, Fraction(60), 8))
  995. def test_floats(self):
  996. self.assertEqual(self.func([0.25]*20),
  997. (float, Fraction(5.0), 20))
  998. def test_fractions(self):
  999. self.assertEqual(self.func([Fraction(1, 1000)]*500),
  1000. (Fraction, Fraction(1, 2), 500))
  1001. def test_decimals(self):
  1002. D = Decimal
  1003. data = [D("0.001"), D("5.246"), D("1.702"), D("-0.025"),
  1004. D("3.974"), D("2.328"), D("4.617"), D("2.843"),
  1005. ]
  1006. self.assertEqual(self.func(data),
  1007. (Decimal, Decimal("20.686"), 8))
  1008. def test_compare_with_math_fsum(self):
  1009. # Compare with the math.fsum function.
  1010. # Ideally we ought to get the exact same result, but sometimes
  1011. # we differ by a very slight amount :-(
  1012. data = [random.uniform(-100, 1000) for _ in range(1000)]
  1013. self.assertApproxEqual(float(self.func(data)[1]), math.fsum(data), rel=2e-16)
  1014. def test_strings_fail(self):
  1015. # Sum of strings should fail.
  1016. self.assertRaises(TypeError, self.func, [1, 2, 3], '999')
  1017. self.assertRaises(TypeError, self.func, [1, 2, 3, '999'])
  1018. def test_bytes_fail(self):
  1019. # Sum of bytes should fail.
  1020. self.assertRaises(TypeError, self.func, [1, 2, 3], b'999')
  1021. self.assertRaises(TypeError, self.func, [1, 2, 3, b'999'])
  1022. def test_mixed_sum(self):
  1023. # Mixed input types are not (currently) allowed.
  1024. # Check that mixed data types fail.
  1025. self.assertRaises(TypeError, self.func, [1, 2.0, Decimal(1)])
  1026. # And so does mixed start argument.
  1027. self.assertRaises(TypeError, self.func, [1, 2.0], Decimal(1))
  1028. class SumTortureTest(NumericTestCase):
  1029. def test_torture(self):
  1030. # Tim Peters' torture test for sum, and variants of same.
  1031. self.assertEqual(statistics._sum([1, 1e100, 1, -1e100]*10000),
  1032. (float, Fraction(20000.0), 40000))
  1033. self.assertEqual(statistics._sum([1e100, 1, 1, -1e100]*10000),
  1034. (float, Fraction(20000.0), 40000))
  1035. T, num, count = statistics._sum([1e-100, 1, 1e-100, -1]*10000)
  1036. self.assertIs(T, float)
  1037. self.assertEqual(count, 40000)
  1038. self.assertApproxEqual(float(num), 2.0e-96, rel=5e-16)
  1039. class SumSpecialValues(NumericTestCase):
  1040. # Test that sum works correctly with IEEE-754 special values.
  1041. def test_nan(self):
  1042. for type_ in (float, Decimal):
  1043. nan = type_('nan')
  1044. result = statistics._sum([1, nan, 2])[1]
  1045. self.assertIs(type(result), type_)
  1046. self.assertTrue(math.isnan(result))
  1047. def check_infinity(self, x, inf):
  1048. """Check x is an infinity of the same type and sign as inf."""
  1049. self.assertTrue(math.isinf(x))
  1050. self.assertIs(type(x), type(inf))
  1051. self.assertEqual(x > 0, inf > 0)
  1052. assert x == inf
  1053. def do_test_inf(self, inf):
  1054. # Adding a single infinity gives infinity.
  1055. result = statistics._sum([1, 2, inf, 3])[1]
  1056. self.check_infinity(result, inf)
  1057. # Adding two infinities of the same sign also gives infinity.
  1058. result = statistics._sum([1, 2, inf, 3, inf, 4])[1]
  1059. self.check_infinity(result, inf)
  1060. def test_float_inf(self):
  1061. inf = float('inf')
  1062. for sign in (+1, -1):
  1063. self.do_test_inf(sign*inf)
  1064. def test_decimal_inf(self):
  1065. inf = Decimal('inf')
  1066. for sign in (+1, -1):
  1067. self.do_test_inf(sign*inf)
  1068. def test_float_mismatched_infs(self):
  1069. # Test that adding two infinities of opposite sign gives a NAN.
  1070. inf = float('inf')
  1071. result = statistics._sum([1, 2, inf, 3, -inf, 4])[1]
  1072. self.assertTrue(math.isnan(result))
  1073. def test_decimal_extendedcontext_mismatched_infs_to_nan(self):
  1074. # Test adding Decimal INFs with opposite sign returns NAN.
  1075. inf = Decimal('inf')
  1076. data = [1, 2, inf, 3, -inf, 4]
  1077. with decimal.localcontext(decimal.ExtendedContext):
  1078. self.assertTrue(math.isnan(statistics._sum(data)[1]))
  1079. def test_decimal_basiccontext_mismatched_infs_to_nan(self):
  1080. # Test adding Decimal INFs with opposite sign raises InvalidOperation.
  1081. inf = Decimal('inf')
  1082. data = [1, 2, inf, 3, -inf, 4]
  1083. with decimal.localcontext(decimal.BasicContext):
  1084. self.assertRaises(decimal.InvalidOperation, statistics._sum, data)
  1085. def test_decimal_snan_raises(self):
  1086. # Adding sNAN should raise InvalidOperation.
  1087. sNAN = Decimal('sNAN')
  1088. data = [1, sNAN, 2]
  1089. self.assertRaises(decimal.InvalidOperation, statistics._sum, data)
  1090. # === Tests for averages ===
  1091. class AverageMixin(UnivariateCommonMixin):
  1092. # Mixin class holding common tests for averages.
  1093. def test_single_value(self):
  1094. # Average of a single value is the value itself.
  1095. for x in (23, 42.5, 1.3e15, Fraction(15, 19), Decimal('0.28')):
  1096. self.assertEqual(self.func([x]), x)
  1097. def prepare_values_for_repeated_single_test(self):
  1098. return (3.5, 17, 2.5e15, Fraction(61, 67), Decimal('4.9712'))
  1099. def test_repeated_single_value(self):
  1100. # The average of a single repeated value is the value itself.
  1101. for x in self.prepare_values_for_repeated_single_test():
  1102. for count in (2, 5, 10, 20):
  1103. with self.subTest(x=x, count=count):
  1104. data = [x]*count
  1105. self.assertEqual(self.func(data), x)
  1106. class TestMean(NumericTestCase, AverageMixin, UnivariateTypeMixin):
  1107. def setUp(self):
  1108. self.func = statistics.mean
  1109. def test_torture_pep(self):
  1110. # "Torture Test" from PEP-450.
  1111. self.assertEqual(self.func([1e100, 1, 3, -1e100]), 1)
  1112. def test_ints(self):
  1113. # Test mean with ints.
  1114. data = [0, 1, 2, 3, 3, 3, 4, 5, 5, 6, 7, 7, 7, 7, 8, 9]
  1115. random.shuffle(data)
  1116. self.assertEqual(self.func(data), 4.8125)
  1117. def test_floats(self):
  1118. # Test mean with floats.
  1119. data = [17.25, 19.75, 20.0, 21.5, 21.75, 23.25, 25.125, 27.5]
  1120. random.shuffle(data)
  1121. self.assertEqual(self.func(data), 22.015625)
  1122. def test_decimals(self):
  1123. # Test mean with Decimals.
  1124. D = Decimal
  1125. data = [D("1.634"), D("2.517"), D("3.912"), D("4.072"), D("5.813")]
  1126. random.shuffle(data)
  1127. self.assertEqual(self.func(data), D("3.5896"))
  1128. def test_fractions(self):
  1129. # Test mean with Fractions.
  1130. F = Fraction
  1131. data = [F(1, 2), F(2, 3), F(3, 4), F(4, 5), F(5, 6), F(6, 7), F(7, 8)]
  1132. random.shuffle(data)
  1133. self.assertEqual(self.func(data), F(1479, 1960))
  1134. def test_inf(self):
  1135. # Test mean with infinities.
  1136. raw = [1, 3, 5, 7, 9] # Use only ints, to avoid TypeError later.
  1137. for kind in (float, Decimal):
  1138. for sign in (1, -1):
  1139. inf = kind("inf")*sign
  1140. data = raw + [inf]
  1141. result = self.func(data)
  1142. self.assertTrue(math.isinf(result))
  1143. self.assertEqual(result, inf)
  1144. def test_mismatched_infs(self):
  1145. # Test mean with infinities of opposite sign.
  1146. data = [2, 4, 6, float('inf'), 1, 3, 5, float('-inf')]
  1147. result = self.func(data)
  1148. self.assertTrue(math.isnan(result))
  1149. def test_nan(self):
  1150. # Test mean with NANs.
  1151. raw = [1, 3, 5, 7, 9] # Use only ints, to avoid TypeError later.
  1152. for kind in (float, Decimal):
  1153. inf = kind("nan")
  1154. data = raw + [inf]
  1155. result = self.func(data)
  1156. self.assertTrue(math.isnan(result))
  1157. def test_big_data(self):
  1158. # Test adding a large constant to every data point.
  1159. c = 1e9
  1160. data = [3.4, 4.5, 4.9, 6.7, 6.8, 7.2, 8.0, 8.1, 9.4]
  1161. expected = self.func(data) + c
  1162. assert expected != c
  1163. result = self.func([x+c for x in data])
  1164. self.assertEqual(result, expected)
  1165. def test_doubled_data(self):
  1166. # Mean of [a,b,c...z] should be same as for [a,a,b,b,c,c...z,z].
  1167. data = [random.uniform(-3, 5) for _ in range(1000)]
  1168. expected = self.func(data)
  1169. actual = self.func(data*2)
  1170. self.assertApproxEqual(actual, expected)
  1171. def test_regression_20561(self):
  1172. # Regression test for issue 20561.
  1173. # See http://bugs.python.org/issue20561
  1174. d = Decimal('1e4')
  1175. self.assertEqual(statistics.mean([d]), d)
  1176. def test_regression_25177(self):
  1177. # Regression test for issue 25177.
  1178. # Ensure very big and very small floats don't overflow.
  1179. # See http://bugs.python.org/issue25177.
  1180. self.assertEqual(statistics.mean(
  1181. [8.988465674311579e+307, 8.98846567431158e+307]),
  1182. 8.98846567431158e+307)
  1183. big = 8.98846567431158e+307
  1184. tiny = 5e-324
  1185. for n in (2, 3, 5, 200):
  1186. self.assertEqual(statistics.mean([big]*n), big)
  1187. self.assertEqual(statistics.mean([tiny]*n), tiny)
  1188. class TestHarmonicMean(NumericTestCase, AverageMixin, UnivariateTypeMixin):
  1189. def setUp(self):
  1190. self.func = statistics.harmonic_mean
  1191. def prepare_data(self):
  1192. # Override mixin method.
  1193. values = super().prepare_data()
  1194. values.remove(0)
  1195. return values
  1196. def prepare_values_for_repeated_single_test(self):
  1197. # Override mixin method.
  1198. return (3.5, 17, 2.5e15, Fraction(61, 67), Decimal('4.125'))
  1199. def test_zero(self):
  1200. # Test that harmonic mean returns zero when given zero.
  1201. values = [1, 0, 2]
  1202. self.assertEqual(self.func(values), 0)
  1203. def test_negative_error(self):
  1204. # Test that harmonic mean raises when given a negative value.
  1205. exc = statistics.StatisticsError
  1206. for values in ([-1], [1, -2, 3]):
  1207. with self.subTest(values=values):
  1208. self.assertRaises(exc, self.func, values)
  1209. def test_invalid_type_error(self):
  1210. # Test error is raised when input contains invalid type(s)
  1211. for data in [
  1212. ['3.14'], # single string
  1213. ['1', '2', '3'], # multiple strings
  1214. [1, '2', 3, '4', 5], # mixed strings and valid integers
  1215. [2.3, 3.4, 4.5, '5.6'] # only one string and valid floats
  1216. ]:
  1217. with self.subTest(data=data):
  1218. with self.assertRaises(TypeError):
  1219. self.func(data)
  1220. def test_ints(self):
  1221. # Test harmonic mean with ints.
  1222. data = [2, 4, 4, 8, 16, 16]
  1223. random.shuffle(data)
  1224. self.assertEqual(self.func(data), 6*4/5)
  1225. def test_floats_exact(self):
  1226. # Test harmonic mean with some carefully chosen floats.
  1227. data = [1/8, 1/4, 1/4, 1/2, 1/2]
  1228. random.shuffle(data)
  1229. self.assertEqual(self.func(data), 1/4)
  1230. self.assertEqual(self.func([0.25, 0.5, 1.0, 1.0]), 0.5)
  1231. def test_singleton_lists(self):
  1232. # Test that harmonic mean([x]) returns (approximately) x.
  1233. for x in range(1, 101):
  1234. self.assertEqual(self.func([x]), x)
  1235. def test_decimals_exact(self):
  1236. # Test harmonic mean with some carefully chosen Decimals.
  1237. D = Decimal
  1238. self.assertEqual(self.func([D(15), D(30), D(60), D(60)]), D(30))
  1239. data = [D("0.05"), D("0.10"), D("0.20"), D("0.20")]
  1240. random.shuffle(data)
  1241. self.assertEqual(self.func(data), D("0.10"))
  1242. data = [D("1.68"), D("0.32"), D("5.94"), D("2.75")]
  1243. random.shuffle(data)
  1244. self.assertEqual(self.func(data), D(66528)/70723)
  1245. def test_fractions(self):
  1246. # Test harmonic mean with Fractions.
  1247. F = Fraction
  1248. data = [F(1, 2), F(2, 3), F(3, 4), F(4, 5), F(5, 6), F(6, 7), F(7, 8)]
  1249. random.shuffle(data)
  1250. self.assertEqual(self.func(data), F(7*420, 4029))
  1251. def test_inf(self):
  1252. # Test harmonic mean with infinity.
  1253. values = [2.0, float('inf'), 1.0]
  1254. self.assertEqual(self.func(values), 2.0)
  1255. def test_nan(self):
  1256. # Test harmonic mean with NANs.
  1257. values = [2.0, float('nan'), 1.0]
  1258. self.assertTrue(math.isnan(self.func(values)))
  1259. def test_multiply_data_points(self):
  1260. # Test multiplying every data point by a constant.
  1261. c = 111
  1262. data = [3.4, 4.5, 4.9, 6.7, 6.8, 7.2, 8.0, 8.1, 9.4]
  1263. expected = self.func(data)*c
  1264. result = self.func([x*c for x in data])
  1265. self.assertEqual(result, expected)
  1266. def test_doubled_data(self):
  1267. # Harmonic mean of [a,b...z] should be same as for [a,a,b,b...z,z].
  1268. data = [random.uniform(1, 5) for _ in range(1000)]
  1269. expected = self.func(data)
  1270. actual = self.func(data*2)
  1271. self.assertApproxEqual(actual, expected)
  1272. def test_with_weights(self):
  1273. self.assertEqual(self.func([40, 60], [5, 30]), 56.0) # common case
  1274. self.assertEqual(self.func([40, 60],
  1275. weights=[5, 30]), 56.0) # keyword argument
  1276. self.assertEqual(self.func(iter([40, 60]),
  1277. iter([5, 30])), 56.0) # iterator inputs
  1278. self.assertEqual(
  1279. self.func([Fraction(10, 3), Fraction(23, 5), Fraction(7, 2)], [5, 2, 10]),
  1280. self.func([Fraction(10, 3)] * 5 +
  1281. [Fraction(23, 5)] * 2 +
  1282. [Fraction(7, 2)] * 10))
  1283. self.assertEqual(self.func([10], [7]), 10) # n=1 fast path
  1284. with self.assertRaises(TypeError):
  1285. self.func([1, 2, 3], [1, (), 3]) # non-numeric weight
  1286. with self.assertRaises(statistics.StatisticsError):
  1287. self.func([1, 2, 3], [1, 2]) # wrong number of weights
  1288. with self.assertRaises(statistics.StatisticsError):
  1289. self.func([10], [0]) # no non-zero weights
  1290. with self.assertRaises(statistics.StatisticsError):
  1291. self.func([10, 20], [0, 0]) # no non-zero weights
  1292. class TestMedian(NumericTestCase, AverageMixin):
  1293. # Common tests for median and all median.* functions.
  1294. def setUp(self):
  1295. self.func = statistics.median
  1296. def prepare_data(self):
  1297. """Overload method from UnivariateCommonMixin."""
  1298. data = super().prepare_data()
  1299. if len(data)%2 != 1:
  1300. data.append(2)
  1301. return data
  1302. def test_even_ints(self):
  1303. # Test median with an even number of int data points.
  1304. data = [1, 2, 3, 4, 5, 6]
  1305. assert len(data)%2 == 0
  1306. self.assertEqual(self.func(data), 3.5)
  1307. def test_odd_ints(self):
  1308. # Test median with an odd number of int data points.
  1309. data = [1, 2, 3, 4, 5, 6, 9]
  1310. assert len(data)%2 == 1
  1311. self.assertEqual(self.func(data), 4)
  1312. def test_odd_fractions(self):
  1313. # Test median works with an odd number of Fractions.
  1314. F = Fraction
  1315. data = [F(1, 7), F(2, 7), F(3, 7), F(4, 7), F(5, 7)]
  1316. assert len(data)%2 == 1
  1317. random.shuffle(data)
  1318. self.assertEqual(self.func(data), F(3, 7))
  1319. def test_even_fractions(self):
  1320. # Test median works with an even number of Fractions.
  1321. F = Fraction
  1322. data = [F(1, 7), F(2, 7), F(3, 7), F(4, 7), F(5, 7), F(6, 7)]
  1323. assert len(data)%2 == 0
  1324. random.shuffle(data)
  1325. self.assertEqual(self.func(data), F(1, 2))
  1326. def test_odd_decimals(self):
  1327. # Test median works with an odd number of Decimals.
  1328. D = Decimal
  1329. data = [D('2.5'), D('3.1'), D('4.2'), D('5.7'), D('5.8')]
  1330. assert len(data)%2 == 1
  1331. random.shuffle(data)
  1332. self.assertEqual(self.func(data), D('4.2'))
  1333. def test_even_decimals(self):
  1334. # Test median works with an even number of Decimals.
  1335. D = Decimal
  1336. data = [D('1.2'), D('2.5'), D('3.1'), D('4.2'), D('5.7'), D('5.8')]
  1337. assert len(data)%2 == 0
  1338. random.shuffle(data)
  1339. self.assertEqual(self.func(data), D('3.65'))
  1340. class TestMedianDataType(NumericTestCase, UnivariateTypeMixin):
  1341. # Test conservation of data element type for median.
  1342. def setUp(self):
  1343. self.func = statistics.median
  1344. def prepare_data(self):
  1345. data = list(range(15))
  1346. assert len(data)%2 == 1
  1347. while data == sorted(data):
  1348. random.shuffle(data)
  1349. return data
  1350. class TestMedianLow(TestMedian, UnivariateTypeMixin):
  1351. def setUp(self):
  1352. self.func = statistics.median_low
  1353. def test_even_ints(self):
  1354. # Test median_low with an even number of ints.
  1355. data = [1, 2, 3, 4, 5, 6]
  1356. assert len(data)%2 == 0
  1357. self.assertEqual(self.func(data), 3)
  1358. def test_even_fractions(self):
  1359. # Test median_low works with an even number of Fractions.
  1360. F = Fraction
  1361. data = [F(1, 7), F(2, 7), F(3, 7), F(4, 7), F(5, 7), F(6, 7)]
  1362. assert len(data)%2 == 0
  1363. random.shuffle(data)
  1364. self.assertEqual(self.func(data), F(3, 7))
  1365. def test_even_decimals(self):
  1366. # Test median_low works with an even number of Decimals.
  1367. D = Decimal
  1368. data = [D('1.1'), D('2.2'), D('3.3'), D('4.4'), D('5.5'), D('6.6')]
  1369. assert len(data)%2 == 0
  1370. random.shuffle(data)
  1371. self.assertEqual(self.func(data), D('3.3'))
  1372. class TestMedianHigh(TestMedian, UnivariateTypeMixin):
  1373. def setUp(self):
  1374. self.func = statistics.median_high
  1375. def test_even_ints(self):
  1376. # Test median_high with an even number of ints.
  1377. data = [1, 2, 3, 4, 5, 6]
  1378. assert len(data)%2 == 0
  1379. self.assertEqual(self.func(data), 4)
  1380. def test_even_fractions(self):
  1381. # Test median_high works with an even number of Fractions.
  1382. F = Fraction
  1383. data = [F(1, 7), F(2, 7), F(3, 7), F(4, 7), F(5, 7), F(6, 7)]
  1384. assert len(data)%2 == 0
  1385. random.shuffle(data)
  1386. self.assertEqual(self.func(data), F(4, 7))
  1387. def test_even_decimals(self):
  1388. # Test median_high works with an even number of Decimals.
  1389. D = Decimal
  1390. data = [D('1.1'), D('2.2'), D('3.3'), D('4.4'), D('5.5'), D('6.6')]
  1391. assert len(data)%2 == 0
  1392. random.shuffle(data)
  1393. self.assertEqual(self.func(data), D('4.4'))
  1394. class TestMedianGrouped(TestMedian):
  1395. # Test median_grouped.
  1396. # Doesn't conserve data element types, so don't use TestMedianType.
  1397. def setUp(self):
  1398. self.func = statistics.median_grouped
  1399. def test_odd_number_repeated(self):
  1400. # Test median.grouped with repeated median values.
  1401. data = [12, 13, 14, 14, 14, 15, 15]
  1402. assert len(data)%2 == 1
  1403. self.assertEqual(self.func(data), 14)
  1404. #---
  1405. data = [12, 13, 14, 14, 14, 14, 15]
  1406. assert len(data)%2 == 1
  1407. self.assertEqual(self.func(data), 13.875)
  1408. #---
  1409. data = [5, 10, 10, 15, 20, 20, 20, 20, 25, 25, 30]
  1410. assert len(data)%2 == 1
  1411. self.assertEqual(self.func(data, 5), 19.375)
  1412. #---
  1413. data = [16, 18, 18, 18, 18, 20, 20, 20, 22, 22, 22, 24, 24, 26, 28]
  1414. assert len(data)%2 == 1
  1415. self.assertApproxEqual(self.func(data, 2), 20.66666667, tol=1e-8)
  1416. def test_even_number_repeated(self):
  1417. # Test median.grouped with repeated median values.
  1418. data = [5, 10, 10, 15, 20, 20, 20, 25, 25, 30]
  1419. assert len(data)%2 == 0
  1420. self.assertApproxEqual(self.func(data, 5), 19.16666667, tol=1e-8)
  1421. #---
  1422. data = [2, 3, 4, 4, 4, 5]
  1423. assert len(data)%2 == 0
  1424. self.assertApproxEqual(self.func(data), 3.83333333, tol=1e-8)
  1425. #---
  1426. data = [2, 3, 3, 4, 4, 4, 5, 5, 5, 5, 6, 6]
  1427. assert len(data)%2 == 0
  1428. self.assertEqual(self.func(data), 4.5)
  1429. #---
  1430. data = [3, 4, 4, 4, 5, 5, 5, 5, 6, 6]
  1431. assert len(data)%2 == 0
  1432. self.assertEqual(self.func(data), 4.75)
  1433. def test_repeated_single_value(self):
  1434. # Override method from AverageMixin.
  1435. # Yet again, failure of median_grouped to conserve the data type
  1436. # causes me headaches :-(
  1437. for x in (5.3, 68, 4.3e17, Fraction(29, 101), Decimal('32.9714')):
  1438. for count in (2, 5, 10, 20):
  1439. data = [x]*count
  1440. self.assertEqual(self.func(data), float(x))
  1441. def test_single_value(self):
  1442. # Override method from AverageMixin.
  1443. # Average of a single value is the value as a float.
  1444. for x in (23, 42.5, 1.3e15, Fraction(15, 19), Decimal('0.28')):
  1445. self.assertEqual(self.func([x]), float(x))
  1446. def test_odd_fractions(self):
  1447. # Test median_grouped works with an odd number of Fractions.
  1448. F = Fraction
  1449. data = [F(5, 4), F(9, 4), F(13, 4), F(13, 4), F(17, 4)]
  1450. assert len(data)%2 == 1
  1451. random.shuffle(data)
  1452. self.assertEqual(self.func(data), 3.0)
  1453. def test_even_fractions(self):
  1454. # Test median_grouped works with an even number of Fractions.
  1455. F = Fraction
  1456. data = [F(5, 4), F(9, 4), F(13, 4), F(13, 4), F(17, 4), F(17, 4)]
  1457. assert len(data)%2 == 0
  1458. random.shuffle(data)
  1459. self.assertEqual(self.func(data), 3.25)
  1460. def test_odd_decimals(self):
  1461. # Test median_grouped works with an odd number of Decimals.
  1462. D = Decimal
  1463. data = [D('5.5'), D('6.5'), D('6.5'), D('7.5'), D('8.5')]
  1464. assert len(data)%2 == 1
  1465. random.shuffle(data)
  1466. self.assertEqual(self.func(data), 6.75)
  1467. def test_even_decimals(self):
  1468. # Test median_grouped works with an even number of Decimals.
  1469. D = Decimal
  1470. data = [D('5.5'), D('5.5'), D('6.5'), D('6.5'), D('7.5'), D('8.5')]
  1471. assert len(data)%2 == 0
  1472. random.shuffle(data)
  1473. self.assertEqual(self.func(data), 6.5)
  1474. #---
  1475. data = [D('5.5'), D('5.5'), D('6.5'), D('7.5'), D('7.5'), D('8.5')]
  1476. assert len(data)%2 == 0
  1477. random.shuffle(data)
  1478. self.assertEqual(self.func(data), 7.0)
  1479. def test_interval(self):
  1480. # Test median_grouped with interval argument.
  1481. data = [2.25, 2.5, 2.5, 2.75, 2.75, 3.0, 3.0, 3.25, 3.5, 3.75]
  1482. self.assertEqual(self.func(data, 0.25), 2.875)
  1483. data = [2.25, 2.5, 2.5, 2.75, 2.75, 2.75, 3.0, 3.0, 3.25, 3.5, 3.75]
  1484. self.assertApproxEqual(self.func(data, 0.25), 2.83333333, tol=1e-8)
  1485. data = [220, 220, 240, 260, 260, 260, 260, 280, 280, 300, 320, 340]
  1486. self.assertEqual(self.func(data, 20), 265.0)
  1487. def test_data_type_error(self):
  1488. # Test median_grouped with str, bytes data types for data and interval
  1489. data = ["", "", ""]
  1490. self.assertRaises(TypeError, self.func, data)
  1491. #---
  1492. data = [b"", b"", b""]
  1493. self.assertRaises(TypeError, self.func, data)
  1494. #---
  1495. data = [1, 2, 3]
  1496. interval = ""
  1497. self.assertRaises(TypeError, self.func, data, interval)
  1498. #---
  1499. data = [1, 2, 3]
  1500. interval = b""
  1501. self.assertRaises(TypeError, self.func, data, interval)
  1502. class TestMode(NumericTestCase, AverageMixin, UnivariateTypeMixin):
  1503. # Test cases for the discrete version of mode.
  1504. def setUp(self):
  1505. self.func = statistics.mode
  1506. def prepare_data(self):
  1507. """Overload method from UnivariateCommonMixin."""
  1508. # Make sure test data has exactly one mode.
  1509. return [1, 1, 1, 1, 3, 4, 7, 9, 0, 8, 2]
  1510. def test_range_data(self):
  1511. # Override test from UnivariateCommonMixin.
  1512. data = range(20, 50, 3)
  1513. self.assertEqual(self.func(data), 20)
  1514. def test_nominal_data(self):
  1515. # Test mode with nominal data.
  1516. data = 'abcbdb'
  1517. self.assertEqual(self.func(data), 'b')
  1518. data = 'fe fi fo fum fi fi'.split()
  1519. self.assertEqual(self.func(data), 'fi')
  1520. def test_discrete_data(self):
  1521. # Test mode with discrete numeric data.
  1522. data = list(range(10))
  1523. for i in range(10):
  1524. d = data + [i]
  1525. random.shuffle(d)
  1526. self.assertEqual(self.func(d), i)
  1527. def test_bimodal_data(self):
  1528. # Test mode with bimodal data.
  1529. data = [1, 1, 2, 2, 2, 2, 3, 4, 5, 6, 6, 6, 6, 7, 8, 9, 9]
  1530. assert data.count(2) == data.count(6) == 4
  1531. # mode() should return 2, the first encountered mode
  1532. self.assertEqual(self.func(data), 2)
  1533. def test_unique_data(self):
  1534. # Test mode when data points are all unique.
  1535. data = list(range(10))
  1536. # mode() should return 0, the first encountered mode
  1537. self.assertEqual(self.func(data), 0)
  1538. def test_none_data(self):
  1539. # Test that mode raises TypeError if given None as data.
  1540. # This test is necessary because the implementation of mode uses
  1541. # collections.Counter, which accepts None and returns an empty dict.
  1542. self.assertRaises(TypeError, self.func, None)
  1543. def test_counter_data(self):
  1544. # Test that a Counter is treated like any other iterable.
  1545. # We're making sure mode() first calls iter() on its input.
  1546. # The concern is that a Counter of a Counter returns the original
  1547. # unchanged rather than counting its keys.
  1548. c = collections.Counter(a=1, b=2)
  1549. # If iter() is called, mode(c) loops over the keys, ['a', 'b'],
  1550. # all the counts will be 1, and the first encountered mode is 'a'.
  1551. self.assertEqual(self.func(c), 'a')
  1552. class TestMultiMode(unittest.TestCase):
  1553. def test_basics(self):
  1554. multimode = statistics.multimode
  1555. self.assertEqual(multimode('aabbbbbbbbcc'), ['b'])
  1556. self.assertEqual(multimode('aabbbbccddddeeffffgg'), ['b', 'd', 'f'])
  1557. self.assertEqual(multimode(''), [])
  1558. class TestFMean(unittest.TestCase):
  1559. def test_basics(self):
  1560. fmean = statistics.fmean
  1561. D = Decimal
  1562. F = Fraction
  1563. for data, expected_mean, kind in [
  1564. ([3.5, 4.0, 5.25], 4.25, 'floats'),
  1565. ([D('3.5'), D('4.0'), D('5.25')], 4.25, 'decimals'),
  1566. ([F(7, 2), F(4, 1), F(21, 4)], 4.25, 'fractions'),
  1567. ([True, False, True, True, False], 0.60, 'booleans'),
  1568. ([3.5, 4, F(21, 4)], 4.25, 'mixed types'),
  1569. ((3.5, 4.0, 5.25), 4.25, 'tuple'),
  1570. (iter([3.5, 4.0, 5.25]), 4.25, 'iterator'),
  1571. ]:
  1572. actual_mean = fmean(data)
  1573. self.assertIs(type(actual_mean), float, kind)
  1574. self.assertEqual(actual_mean, expected_mean, kind)
  1575. def test_error_cases(self):
  1576. fmean = statistics.fmean
  1577. StatisticsError = statistics.StatisticsError
  1578. with self.assertRaises(StatisticsError):
  1579. fmean([]) # empty input
  1580. with self.assertRaises(StatisticsError):
  1581. fmean(iter([])) # empty iterator
  1582. with self.assertRaises(TypeError):
  1583. fmean(None) # non-iterable input
  1584. with self.assertRaises(TypeError):
  1585. fmean([10, None, 20]) # non-numeric input
  1586. with self.assertRaises(TypeError):
  1587. fmean() # missing data argument
  1588. with self.assertRaises(TypeError):
  1589. fmean([10, 20, 60], 70) # too many arguments
  1590. def test_special_values(self):
  1591. # Rules for special values are inherited from math.fsum()
  1592. fmean = statistics.fmean
  1593. NaN = float('Nan')
  1594. Inf = float('Inf')
  1595. self.assertTrue(math.isnan(fmean([10, NaN])), 'nan')
  1596. self.assertTrue(math.isnan(fmean([NaN, Inf])), 'nan and infinity')
  1597. self.assertTrue(math.isinf(fmean([10, Inf])), 'infinity')
  1598. with self.assertRaises(ValueError):
  1599. fmean([Inf, -Inf])
  1600. def test_weights(self):
  1601. fmean = statistics.fmean
  1602. StatisticsError = statistics.StatisticsError
  1603. self.assertEqual(
  1604. fmean([10, 10, 10, 50], [0.25] * 4),
  1605. fmean([10, 10, 10, 50]))
  1606. self.assertEqual(
  1607. fmean([10, 10, 20], [0.25, 0.25, 0.50]),
  1608. fmean([10, 10, 20, 20]))
  1609. self.assertEqual( # inputs are iterators
  1610. fmean(iter([10, 10, 20]), iter([0.25, 0.25, 0.50])),
  1611. fmean([10, 10, 20, 20]))
  1612. with self.assertRaises(StatisticsError):
  1613. fmean([10, 20, 30], [1, 2]) # unequal lengths
  1614. with self.assertRaises(StatisticsError):
  1615. fmean(iter([10, 20, 30]), iter([1, 2])) # unequal lengths
  1616. with self.assertRaises(StatisticsError):
  1617. fmean([10, 20], [-1, 1]) # sum of weights is zero
  1618. with self.assertRaises(StatisticsError):
  1619. fmean(iter([10, 20]), iter([-1, 1])) # sum of weights is zero
  1620. # === Tests for variances and standard deviations ===
  1621. class VarianceStdevMixin(UnivariateCommonMixin):
  1622. # Mixin class holding common tests for variance and std dev.
  1623. # Subclasses should inherit from this before NumericTestClass, in order
  1624. # to see the rel attribute below. See testShiftData for an explanation.
  1625. rel = 1e-12
  1626. def test_single_value(self):
  1627. # Deviation of a single value is zero.
  1628. for x in (11, 19.8, 4.6e14, Fraction(21, 34), Decimal('8.392')):
  1629. self.assertEqual(self.func([x]), 0)
  1630. def test_repeated_single_value(self):
  1631. # The deviation of a single repeated value is zero.
  1632. for x in (7.2, 49, 8.1e15, Fraction(3, 7), Decimal('62.4802')):
  1633. for count in (2, 3, 5, 15):
  1634. data = [x]*count
  1635. self.assertEqual(self.func(data), 0)
  1636. def test_domain_error_regression(self):
  1637. # Regression test for a domain error exception.
  1638. # (Thanks to Geremy Condra.)
  1639. data = [0.123456789012345]*10000
  1640. # All the items are identical, so variance should be exactly zero.
  1641. # We allow some small round-off error, but not much.
  1642. result = self.func(data)
  1643. self.assertApproxEqual(result, 0.0, tol=5e-17)
  1644. self.assertGreaterEqual(result, 0) # A negative result must fail.
  1645. def test_shift_data(self):
  1646. # Test that shifting the data by a constant amount does not affect
  1647. # the variance or stdev. Or at least not much.
  1648. # Due to rounding, this test should be considered an ideal. We allow
  1649. # some tolerance away from "no change at all" by setting tol and/or rel
  1650. # attributes. Subclasses may set tighter or looser error tolerances.
  1651. raw = [1.03, 1.27, 1.94, 2.04, 2.58, 3.14, 4.75, 4.98, 5.42, 6.78]
  1652. expected = self.func(raw)
  1653. # Don't set shift too high, the bigger it is, the more rounding error.
  1654. shift = 1e5
  1655. data = [x + shift for x in raw]
  1656. self.assertApproxEqual(self.func(data), expected)
  1657. def test_shift_data_exact(self):
  1658. # Like test_shift_data, but result is always exact.
  1659. raw = [1, 3, 3, 4, 5, 7, 9, 10, 11, 16]
  1660. assert all(x==int(x) for x in raw)
  1661. expected = self.func(raw)
  1662. shift = 10**9
  1663. data = [x + shift for x in raw]
  1664. self.assertEqual(self.func(data), expected)
  1665. def test_iter_list_same(self):
  1666. # Test that iter data and list data give the same result.
  1667. # This is an explicit test that iterators and lists are treated the
  1668. # same; justification for this test over and above the similar test
  1669. # in UnivariateCommonMixin is that an earlier design had variance and
  1670. # friends swap between one- and two-pass algorithms, which would
  1671. # sometimes give different results.
  1672. data = [random.uniform(-3, 8) for _ in range(1000)]
  1673. expected = self.func(data)
  1674. self.assertEqual(self.func(iter(data)), expected)
  1675. class TestPVariance(VarianceStdevMixin, NumericTestCase, UnivariateTypeMixin):
  1676. # Tests for population variance.
  1677. def setUp(self):
  1678. self.func = statistics.pvariance
  1679. def test_exact_uniform(self):
  1680. # Test the variance against an exact result for uniform data.
  1681. data = list(range(10000))
  1682. random.shuffle(data)
  1683. expected = (10000**2 - 1)/12 # Exact value.
  1684. self.assertEqual(self.func(data), expected)
  1685. def test_ints(self):
  1686. # Test population variance with int data.
  1687. data = [4, 7, 13, 16]
  1688. exact = 22.5
  1689. self.assertEqual(self.func(data), exact)
  1690. def test_fractions(self):
  1691. # Test population variance with Fraction data.
  1692. F = Fraction
  1693. data = [F(1, 4), F(1, 4), F(3, 4), F(7, 4)]
  1694. exact = F(3, 8)
  1695. result = self.func(data)
  1696. self.assertEqual(result, exact)
  1697. self.assertIsInstance(result, Fraction)
  1698. def test_decimals(self):
  1699. # Test population variance with Decimal data.
  1700. D = Decimal
  1701. data = [D("12.1"), D("12.2"), D("12.5"), D("12.9")]
  1702. exact = D('0.096875')
  1703. result = self.func(data)
  1704. self.assertEqual(result, exact)
  1705. self.assertIsInstance(result, Decimal)
  1706. def test_accuracy_bug_20499(self):
  1707. data = [0, 0, 1]
  1708. exact = 2 / 9
  1709. result = self.func(data)
  1710. self.assertEqual(result, exact)
  1711. self.assertIsInstance(result, float)
  1712. class TestVariance(VarianceStdevMixin, NumericTestCase, UnivariateTypeMixin):
  1713. # Tests for sample variance.
  1714. def setUp(self):
  1715. self.func = statistics.variance
  1716. def test_single_value(self):
  1717. # Override method from VarianceStdevMixin.
  1718. for x in (35, 24.7, 8.2e15, Fraction(19, 30), Decimal('4.2084')):
  1719. self.assertRaises(statistics.StatisticsError, self.func, [x])
  1720. def test_ints(self):
  1721. # Test sample variance with int data.
  1722. data = [4, 7, 13, 16]
  1723. exact = 30
  1724. self.assertEqual(self.func(data), exact)
  1725. def test_fractions(self):
  1726. # Test sample variance with Fraction data.
  1727. F = Fraction
  1728. data = [F(1, 4), F(1, 4), F(3, 4), F(7, 4)]
  1729. exact = F(1, 2)
  1730. result = self.func(data)
  1731. self.assertEqual(result, exact)
  1732. self.assertIsInstance(result, Fraction)
  1733. def test_decimals(self):
  1734. # Test sample variance with Decimal data.
  1735. D = Decimal
  1736. data = [D(2), D(2), D(7), D(9)]
  1737. exact = 4*D('9.5')/D(3)
  1738. result = self.func(data)
  1739. self.assertEqual(result, exact)
  1740. self.assertIsInstance(result, Decimal)
  1741. def test_center_not_at_mean(self):
  1742. data = (1.0, 2.0)
  1743. self.assertEqual(self.func(data), 0.5)
  1744. self.assertEqual(self.func(data, xbar=2.0), 1.0)
  1745. def test_accuracy_bug_20499(self):
  1746. data = [0, 0, 2]
  1747. exact = 4 / 3
  1748. result = self.func(data)
  1749. self.assertEqual(result, exact)
  1750. self.assertIsInstance(result, float)
  1751. class TestPStdev(VarianceStdevMixin, NumericTestCase):
  1752. # Tests for population standard deviation.
  1753. def setUp(self):
  1754. self.func = statistics.pstdev
  1755. def test_compare_to_variance(self):
  1756. # Test that stdev is, in fact, the square root of variance.
  1757. data = [random.uniform(-17, 24) for _ in range(1000)]
  1758. expected = math.sqrt(statistics.pvariance(data))
  1759. self.assertEqual(self.func(data), expected)
  1760. def test_center_not_at_mean(self):
  1761. # See issue: 40855
  1762. data = (3, 6, 7, 10)
  1763. self.assertEqual(self.func(data), 2.5)
  1764. self.assertEqual(self.func(data, mu=0.5), 6.5)
  1765. class TestSqrtHelpers(unittest.TestCase):
  1766. def test_integer_sqrt_of_frac_rto(self):
  1767. for n, m in itertools.product(range(100), range(1, 1000)):
  1768. r = statistics._integer_sqrt_of_frac_rto(n, m)
  1769. self.assertIsInstance(r, int)
  1770. if r*r*m == n:
  1771. # Root is exact
  1772. continue
  1773. # Inexact, so the root should be odd
  1774. self.assertEqual(r&1, 1)
  1775. # Verify correct rounding
  1776. self.assertTrue(m * (r - 1)**2 < n < m * (r + 1)**2)
  1777. @requires_IEEE_754
  1778. def test_float_sqrt_of_frac(self):
  1779. def is_root_correctly_rounded(x: Fraction, root: float) -> bool:
  1780. if not x:
  1781. return root == 0.0
  1782. # Extract adjacent representable floats
  1783. r_up: float = math.nextafter(root, math.inf)
  1784. r_down: float = math.nextafter(root, -math.inf)
  1785. assert r_down < root < r_up
  1786. # Convert to fractions for exact arithmetic
  1787. frac_root: Fraction = Fraction(root)
  1788. half_way_up: Fraction = (frac_root + Fraction(r_up)) / 2
  1789. half_way_down: Fraction = (frac_root + Fraction(r_down)) / 2
  1790. # Check a closed interval.
  1791. # Does not test for a midpoint rounding rule.
  1792. return half_way_down ** 2 <= x <= half_way_up ** 2
  1793. randrange = random.randrange
  1794. for i in range(60_000):
  1795. numerator: int = randrange(10 ** randrange(50))
  1796. denonimator: int = randrange(10 ** randrange(50)) + 1
  1797. with self.subTest(numerator=numerator, denonimator=denonimator):
  1798. x: Fraction = Fraction(numerator, denonimator)
  1799. root: float = statistics._float_sqrt_of_frac(numerator, denonimator)
  1800. self.assertTrue(is_root_correctly_rounded(x, root))
  1801. # Verify that corner cases and error handling match math.sqrt()
  1802. self.assertEqual(statistics._float_sqrt_of_frac(0, 1), 0.0)
  1803. with self.assertRaises(ValueError):
  1804. statistics._float_sqrt_of_frac(-1, 1)
  1805. with self.assertRaises(ValueError):
  1806. statistics._float_sqrt_of_frac(1, -1)
  1807. # Error handling for zero denominator matches that for Fraction(1, 0)
  1808. with self.assertRaises(ZeroDivisionError):
  1809. statistics._float_sqrt_of_frac(1, 0)
  1810. # The result is well defined if both inputs are negative
  1811. self.assertEqual(statistics._float_sqrt_of_frac(-2, -1), statistics._float_sqrt_of_frac(2, 1))
  1812. def test_decimal_sqrt_of_frac(self):
  1813. root: Decimal
  1814. numerator: int
  1815. denominator: int
  1816. for root, numerator, denominator in [
  1817. (Decimal('0.4481904599041192673635338663'), 200874688349065940678243576378, 1000000000000000000000000000000), # No adj
  1818. (Decimal('0.7924949131383786609961759598'), 628048187350206338833590574929, 1000000000000000000000000000000), # Adj up
  1819. (Decimal('0.8500554152289934068192208727'), 722594208960136395984391238251, 1000000000000000000000000000000), # Adj down
  1820. ]:
  1821. with decimal.localcontext(decimal.DefaultContext):
  1822. self.assertEqual(statistics._decimal_sqrt_of_frac(numerator, denominator), root)
  1823. # Confirm expected root with a quad precision decimal computation
  1824. with decimal.localcontext(decimal.DefaultContext) as ctx:
  1825. ctx.prec *= 4
  1826. high_prec_ratio = Decimal(numerator) / Decimal(denominator)
  1827. ctx.rounding = decimal.ROUND_05UP
  1828. high_prec_root = high_prec_ratio.sqrt()
  1829. with decimal.localcontext(decimal.DefaultContext):
  1830. target_root = +high_prec_root
  1831. self.assertEqual(root, target_root)
  1832. # Verify that corner cases and error handling match Decimal.sqrt()
  1833. self.assertEqual(statistics._decimal_sqrt_of_frac(0, 1), 0.0)
  1834. with self.assertRaises(decimal.InvalidOperation):
  1835. statistics._decimal_sqrt_of_frac(-1, 1)
  1836. with self.assertRaises(decimal.InvalidOperation):
  1837. statistics._decimal_sqrt_of_frac(1, -1)
  1838. # Error handling for zero denominator matches that for Fraction(1, 0)
  1839. with self.assertRaises(ZeroDivisionError):
  1840. statistics._decimal_sqrt_of_frac(1, 0)
  1841. # The result is well defined if both inputs are negative
  1842. self.assertEqual(statistics._decimal_sqrt_of_frac(-2, -1), statistics._decimal_sqrt_of_frac(2, 1))
  1843. class TestStdev(VarianceStdevMixin, NumericTestCase):
  1844. # Tests for sample standard deviation.
  1845. def setUp(self):
  1846. self.func = statistics.stdev
  1847. def test_single_value(self):
  1848. # Override method from VarianceStdevMixin.
  1849. for x in (81, 203.74, 3.9e14, Fraction(5, 21), Decimal('35.719')):
  1850. self.assertRaises(statistics.StatisticsError, self.func, [x])
  1851. def test_compare_to_variance(self):
  1852. # Test that stdev is, in fact, the square root of variance.
  1853. data = [random.uniform(-2, 9) for _ in range(1000)]
  1854. expected = math.sqrt(statistics.variance(data))
  1855. self.assertAlmostEqual(self.func(data), expected)
  1856. def test_center_not_at_mean(self):
  1857. data = (1.0, 2.0)
  1858. self.assertEqual(self.func(data, xbar=2.0), 1.0)
  1859. class TestGeometricMean(unittest.TestCase):
  1860. def test_basics(self):
  1861. geometric_mean = statistics.geometric_mean
  1862. self.assertAlmostEqual(geometric_mean([54, 24, 36]), 36.0)
  1863. self.assertAlmostEqual(geometric_mean([4.0, 9.0]), 6.0)
  1864. self.assertAlmostEqual(geometric_mean([17.625]), 17.625)
  1865. random.seed(86753095551212)
  1866. for rng in [
  1867. range(1, 100),
  1868. range(1, 1_000),
  1869. range(1, 10_000),
  1870. range(500, 10_000, 3),
  1871. range(10_000, 500, -3),
  1872. [12, 17, 13, 5, 120, 7],
  1873. [random.expovariate(50.0) for i in range(1_000)],
  1874. [random.lognormvariate(20.0, 3.0) for i in range(2_000)],
  1875. [random.triangular(2000, 3000, 2200) for i in range(3_000)],
  1876. ]:
  1877. gm_decimal = math.prod(map(Decimal, rng)) ** (Decimal(1) / len(rng))
  1878. gm_float = geometric_mean(rng)
  1879. self.assertTrue(math.isclose(gm_float, float(gm_decimal)))
  1880. def test_various_input_types(self):
  1881. geometric_mean = statistics.geometric_mean
  1882. D = Decimal
  1883. F = Fraction
  1884. # https://www.wolframalpha.com/input/?i=geometric+mean+3.5,+4.0,+5.25
  1885. expected_mean = 4.18886
  1886. for data, kind in [
  1887. ([3.5, 4.0, 5.25], 'floats'),
  1888. ([D('3.5'), D('4.0'), D('5.25')], 'decimals'),
  1889. ([F(7, 2), F(4, 1), F(21, 4)], 'fractions'),
  1890. ([3.5, 4, F(21, 4)], 'mixed types'),
  1891. ((3.5, 4.0, 5.25), 'tuple'),
  1892. (iter([3.5, 4.0, 5.25]), 'iterator'),
  1893. ]:
  1894. actual_mean = geometric_mean(data)
  1895. self.assertIs(type(actual_mean), float, kind)
  1896. self.assertAlmostEqual(actual_mean, expected_mean, places=5)
  1897. def test_big_and_small(self):
  1898. geometric_mean = statistics.geometric_mean
  1899. # Avoid overflow to infinity
  1900. large = 2.0 ** 1000
  1901. big_gm = geometric_mean([54.0 * large, 24.0 * large, 36.0 * large])
  1902. self.assertTrue(math.isclose(big_gm, 36.0 * large))
  1903. self.assertFalse(math.isinf(big_gm))
  1904. # Avoid underflow to zero
  1905. small = 2.0 ** -1000
  1906. small_gm = geometric_mean([54.0 * small, 24.0 * small, 36.0 * small])
  1907. self.assertTrue(math.isclose(small_gm, 36.0 * small))
  1908. self.assertNotEqual(small_gm, 0.0)
  1909. def test_error_cases(self):
  1910. geometric_mean = statistics.geometric_mean
  1911. StatisticsError = statistics.StatisticsError
  1912. with self.assertRaises(StatisticsError):
  1913. geometric_mean([]) # empty input
  1914. with self.assertRaises(StatisticsError):
  1915. geometric_mean([3.5, 0.0, 5.25]) # zero input
  1916. with self.assertRaises(StatisticsError):
  1917. geometric_mean([3.5, -4.0, 5.25]) # negative input
  1918. with self.assertRaises(StatisticsError):
  1919. geometric_mean(iter([])) # empty iterator
  1920. with self.assertRaises(TypeError):
  1921. geometric_mean(None) # non-iterable input
  1922. with self.assertRaises(TypeError):
  1923. geometric_mean([10, None, 20]) # non-numeric input
  1924. with self.assertRaises(TypeError):
  1925. geometric_mean() # missing data argument
  1926. with self.assertRaises(TypeError):
  1927. geometric_mean([10, 20, 60], 70) # too many arguments
  1928. def test_special_values(self):
  1929. # Rules for special values are inherited from math.fsum()
  1930. geometric_mean = statistics.geometric_mean
  1931. NaN = float('Nan')
  1932. Inf = float('Inf')
  1933. self.assertTrue(math.isnan(geometric_mean([10, NaN])), 'nan')
  1934. self.assertTrue(math.isnan(geometric_mean([NaN, Inf])), 'nan and infinity')
  1935. self.assertTrue(math.isinf(geometric_mean([10, Inf])), 'infinity')
  1936. with self.assertRaises(ValueError):
  1937. geometric_mean([Inf, -Inf])
  1938. def test_mixed_int_and_float(self):
  1939. # Regression test for b.p.o. issue #28327
  1940. geometric_mean = statistics.geometric_mean
  1941. expected_mean = 3.80675409583932
  1942. values = [
  1943. [2, 3, 5, 7],
  1944. [2, 3, 5, 7.0],
  1945. [2, 3, 5.0, 7.0],
  1946. [2, 3.0, 5.0, 7.0],
  1947. [2.0, 3.0, 5.0, 7.0],
  1948. ]
  1949. for v in values:
  1950. with self.subTest(v=v):
  1951. actual_mean = geometric_mean(v)
  1952. self.assertAlmostEqual(actual_mean, expected_mean, places=5)
  1953. class TestQuantiles(unittest.TestCase):
  1954. def test_specific_cases(self):
  1955. # Match results computed by hand and cross-checked
  1956. # against the PERCENTILE.EXC function in MS Excel.
  1957. quantiles = statistics.quantiles
  1958. data = [120, 200, 250, 320, 350]
  1959. random.shuffle(data)
  1960. for n, expected in [
  1961. (1, []),
  1962. (2, [250.0]),
  1963. (3, [200.0, 320.0]),
  1964. (4, [160.0, 250.0, 335.0]),
  1965. (5, [136.0, 220.0, 292.0, 344.0]),
  1966. (6, [120.0, 200.0, 250.0, 320.0, 350.0]),
  1967. (8, [100.0, 160.0, 212.5, 250.0, 302.5, 335.0, 357.5]),
  1968. (10, [88.0, 136.0, 184.0, 220.0, 250.0, 292.0, 326.0, 344.0, 362.0]),
  1969. (12, [80.0, 120.0, 160.0, 200.0, 225.0, 250.0, 285.0, 320.0, 335.0,
  1970. 350.0, 365.0]),
  1971. (15, [72.0, 104.0, 136.0, 168.0, 200.0, 220.0, 240.0, 264.0, 292.0,
  1972. 320.0, 332.0, 344.0, 356.0, 368.0]),
  1973. ]:
  1974. self.assertEqual(expected, quantiles(data, n=n))
  1975. self.assertEqual(len(quantiles(data, n=n)), n - 1)
  1976. # Preserve datatype when possible
  1977. for datatype in (float, Decimal, Fraction):
  1978. result = quantiles(map(datatype, data), n=n)
  1979. self.assertTrue(all(type(x) == datatype) for x in result)
  1980. self.assertEqual(result, list(map(datatype, expected)))
  1981. # Quantiles should be idempotent
  1982. if len(expected) >= 2:
  1983. self.assertEqual(quantiles(expected, n=n), expected)
  1984. # Cross-check against method='inclusive' which should give
  1985. # the same result after adding in minimum and maximum values
  1986. # extrapolated from the two lowest and two highest points.
  1987. sdata = sorted(data)
  1988. lo = 2 * sdata[0] - sdata[1]
  1989. hi = 2 * sdata[-1] - sdata[-2]
  1990. padded_data = data + [lo, hi]
  1991. self.assertEqual(
  1992. quantiles(data, n=n),
  1993. quantiles(padded_data, n=n, method='inclusive'),
  1994. (n, data),
  1995. )
  1996. # Invariant under translation and scaling
  1997. def f(x):
  1998. return 3.5 * x - 1234.675
  1999. exp = list(map(f, expected))
  2000. act = quantiles(map(f, data), n=n)
  2001. self.assertTrue(all(math.isclose(e, a) for e, a in zip(exp, act)))
  2002. # Q2 agrees with median()
  2003. for k in range(2, 60):
  2004. data = random.choices(range(100), k=k)
  2005. q1, q2, q3 = quantiles(data)
  2006. self.assertEqual(q2, statistics.median(data))
  2007. def test_specific_cases_inclusive(self):
  2008. # Match results computed by hand and cross-checked
  2009. # against the PERCENTILE.INC function in MS Excel
  2010. # and against the quantile() function in SciPy.
  2011. quantiles = statistics.quantiles
  2012. data = [100, 200, 400, 800]
  2013. random.shuffle(data)
  2014. for n, expected in [
  2015. (1, []),
  2016. (2, [300.0]),
  2017. (3, [200.0, 400.0]),
  2018. (4, [175.0, 300.0, 500.0]),
  2019. (5, [160.0, 240.0, 360.0, 560.0]),
  2020. (6, [150.0, 200.0, 300.0, 400.0, 600.0]),
  2021. (8, [137.5, 175, 225.0, 300.0, 375.0, 500.0,650.0]),
  2022. (10, [130.0, 160.0, 190.0, 240.0, 300.0, 360.0, 440.0, 560.0, 680.0]),
  2023. (12, [125.0, 150.0, 175.0, 200.0, 250.0, 300.0, 350.0, 400.0,
  2024. 500.0, 600.0, 700.0]),
  2025. (15, [120.0, 140.0, 160.0, 180.0, 200.0, 240.0, 280.0, 320.0, 360.0,
  2026. 400.0, 480.0, 560.0, 640.0, 720.0]),
  2027. ]:
  2028. self.assertEqual(expected, quantiles(data, n=n, method="inclusive"))
  2029. self.assertEqual(len(quantiles(data, n=n, method="inclusive")), n - 1)
  2030. # Preserve datatype when possible
  2031. for datatype in (float, Decimal, Fraction):
  2032. result = quantiles(map(datatype, data), n=n, method="inclusive")
  2033. self.assertTrue(all(type(x) == datatype) for x in result)
  2034. self.assertEqual(result, list(map(datatype, expected)))
  2035. # Invariant under translation and scaling
  2036. def f(x):
  2037. return 3.5 * x - 1234.675
  2038. exp = list(map(f, expected))
  2039. act = quantiles(map(f, data), n=n, method="inclusive")
  2040. self.assertTrue(all(math.isclose(e, a) for e, a in zip(exp, act)))
  2041. # Natural deciles
  2042. self.assertEqual(quantiles([0, 100], n=10, method='inclusive'),
  2043. [10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0])
  2044. self.assertEqual(quantiles(range(0, 101), n=10, method='inclusive'),
  2045. [10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0])
  2046. # Whenever n is smaller than the number of data points, running
  2047. # method='inclusive' should give the same result as method='exclusive'
  2048. # after the two included extreme points are removed.
  2049. data = [random.randrange(10_000) for i in range(501)]
  2050. actual = quantiles(data, n=32, method='inclusive')
  2051. data.remove(min(data))
  2052. data.remove(max(data))
  2053. expected = quantiles(data, n=32)
  2054. self.assertEqual(expected, actual)
  2055. # Q2 agrees with median()
  2056. for k in range(2, 60):
  2057. data = random.choices(range(100), k=k)
  2058. q1, q2, q3 = quantiles(data, method='inclusive')
  2059. self.assertEqual(q2, statistics.median(data))
  2060. def test_equal_inputs(self):
  2061. quantiles = statistics.quantiles
  2062. for n in range(2, 10):
  2063. data = [10.0] * n
  2064. self.assertEqual(quantiles(data), [10.0, 10.0, 10.0])
  2065. self.assertEqual(quantiles(data, method='inclusive'),
  2066. [10.0, 10.0, 10.0])
  2067. def test_equal_sized_groups(self):
  2068. quantiles = statistics.quantiles
  2069. total = 10_000
  2070. data = [random.expovariate(0.2) for i in range(total)]
  2071. while len(set(data)) != total:
  2072. data.append(random.expovariate(0.2))
  2073. data.sort()
  2074. # Cases where the group size exactly divides the total
  2075. for n in (1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000):
  2076. group_size = total // n
  2077. self.assertEqual(
  2078. [bisect.bisect(data, q) for q in quantiles(data, n=n)],
  2079. list(range(group_size, total, group_size)))
  2080. # When the group sizes can't be exactly equal, they should
  2081. # differ by no more than one
  2082. for n in (13, 19, 59, 109, 211, 571, 1019, 1907, 5261, 9769):
  2083. group_sizes = {total // n, total // n + 1}
  2084. pos = [bisect.bisect(data, q) for q in quantiles(data, n=n)]
  2085. sizes = {q - p for p, q in zip(pos, pos[1:])}
  2086. self.assertTrue(sizes <= group_sizes)
  2087. def test_error_cases(self):
  2088. quantiles = statistics.quantiles
  2089. StatisticsError = statistics.StatisticsError
  2090. with self.assertRaises(TypeError):
  2091. quantiles() # Missing arguments
  2092. with self.assertRaises(TypeError):
  2093. quantiles([10, 20, 30], 13, n=4) # Too many arguments
  2094. with self.assertRaises(TypeError):
  2095. quantiles([10, 20, 30], 4) # n is a positional argument
  2096. with self.assertRaises(StatisticsError):
  2097. quantiles([10, 20, 30], n=0) # n is zero
  2098. with self.assertRaises(StatisticsError):
  2099. quantiles([10, 20, 30], n=-1) # n is negative
  2100. with self.assertRaises(TypeError):
  2101. quantiles([10, 20, 30], n=1.5) # n is not an integer
  2102. with self.assertRaises(ValueError):
  2103. quantiles([10, 20, 30], method='X') # method is unknown
  2104. with self.assertRaises(StatisticsError):
  2105. quantiles([10], n=4) # not enough data points
  2106. with self.assertRaises(TypeError):
  2107. quantiles([10, None, 30], n=4) # data is non-numeric
  2108. class TestBivariateStatistics(unittest.TestCase):
  2109. def test_unequal_size_error(self):
  2110. for x, y in [
  2111. ([1, 2, 3], [1, 2]),
  2112. ([1, 2], [1, 2, 3]),
  2113. ]:
  2114. with self.assertRaises(statistics.StatisticsError):
  2115. statistics.covariance(x, y)
  2116. with self.assertRaises(statistics.StatisticsError):
  2117. statistics.correlation(x, y)
  2118. with self.assertRaises(statistics.StatisticsError):
  2119. statistics.linear_regression(x, y)
  2120. def test_small_sample_error(self):
  2121. for x, y in [
  2122. ([], []),
  2123. ([], [1, 2,]),
  2124. ([1, 2,], []),
  2125. ([1,], [1,]),
  2126. ([1,], [1, 2,]),
  2127. ([1, 2,], [1,]),
  2128. ]:
  2129. with self.assertRaises(statistics.StatisticsError):
  2130. statistics.covariance(x, y)
  2131. with self.assertRaises(statistics.StatisticsError):
  2132. statistics.correlation(x, y)
  2133. with self.assertRaises(statistics.StatisticsError):
  2134. statistics.linear_regression(x, y)
  2135. class TestCorrelationAndCovariance(unittest.TestCase):
  2136. def test_results(self):
  2137. for x, y, result in [
  2138. ([1, 2, 3], [1, 2, 3], 1),
  2139. ([1, 2, 3], [-1, -2, -3], -1),
  2140. ([1, 2, 3], [3, 2, 1], -1),
  2141. ([1, 2, 3], [1, 2, 1], 0),
  2142. ([1, 2, 3], [1, 3, 2], 0.5),
  2143. ]:
  2144. self.assertAlmostEqual(statistics.correlation(x, y), result)
  2145. self.assertAlmostEqual(statistics.covariance(x, y), result)
  2146. def test_different_scales(self):
  2147. x = [1, 2, 3]
  2148. y = [10, 30, 20]
  2149. self.assertAlmostEqual(statistics.correlation(x, y), 0.5)
  2150. self.assertAlmostEqual(statistics.covariance(x, y), 5)
  2151. y = [.1, .2, .3]
  2152. self.assertAlmostEqual(statistics.correlation(x, y), 1)
  2153. self.assertAlmostEqual(statistics.covariance(x, y), 0.1)
  2154. class TestLinearRegression(unittest.TestCase):
  2155. def test_constant_input_error(self):
  2156. x = [1, 1, 1,]
  2157. y = [1, 2, 3,]
  2158. with self.assertRaises(statistics.StatisticsError):
  2159. statistics.linear_regression(x, y)
  2160. def test_results(self):
  2161. for x, y, true_intercept, true_slope in [
  2162. ([1, 2, 3], [0, 0, 0], 0, 0),
  2163. ([1, 2, 3], [1, 2, 3], 0, 1),
  2164. ([1, 2, 3], [100, 100, 100], 100, 0),
  2165. ([1, 2, 3], [12, 14, 16], 10, 2),
  2166. ([1, 2, 3], [-1, -2, -3], 0, -1),
  2167. ([1, 2, 3], [21, 22, 23], 20, 1),
  2168. ([1, 2, 3], [5.1, 5.2, 5.3], 5, 0.1),
  2169. ]:
  2170. slope, intercept = statistics.linear_regression(x, y)
  2171. self.assertAlmostEqual(intercept, true_intercept)
  2172. self.assertAlmostEqual(slope, true_slope)
  2173. def test_proportional(self):
  2174. x = [10, 20, 30, 40]
  2175. y = [180, 398, 610, 799]
  2176. slope, intercept = statistics.linear_regression(x, y, proportional=True)
  2177. self.assertAlmostEqual(slope, 20 + 1/150)
  2178. self.assertEqual(intercept, 0.0)
  2179. class TestNormalDist:
  2180. # General note on precision: The pdf(), cdf(), and overlap() methods
  2181. # depend on functions in the math libraries that do not make
  2182. # explicit accuracy guarantees. Accordingly, some of the accuracy
  2183. # tests below may fail if the underlying math functions are
  2184. # inaccurate. There isn't much we can do about this short of
  2185. # implementing our own implementations from scratch.
  2186. def test_slots(self):
  2187. nd = self.module.NormalDist(300, 23)
  2188. with self.assertRaises(TypeError):
  2189. vars(nd)
  2190. self.assertEqual(tuple(nd.__slots__), ('_mu', '_sigma'))
  2191. def test_instantiation_and_attributes(self):
  2192. nd = self.module.NormalDist(500, 17)
  2193. self.assertEqual(nd.mean, 500)
  2194. self.assertEqual(nd.stdev, 17)
  2195. self.assertEqual(nd.variance, 17**2)
  2196. # default arguments
  2197. nd = self.module.NormalDist()
  2198. self.assertEqual(nd.mean, 0)
  2199. self.assertEqual(nd.stdev, 1)
  2200. self.assertEqual(nd.variance, 1**2)
  2201. # error case: negative sigma
  2202. with self.assertRaises(self.module.StatisticsError):
  2203. self.module.NormalDist(500, -10)
  2204. # verify that subclass type is honored
  2205. class NewNormalDist(self.module.NormalDist):
  2206. pass
  2207. nnd = NewNormalDist(200, 5)
  2208. self.assertEqual(type(nnd), NewNormalDist)
  2209. def test_alternative_constructor(self):
  2210. NormalDist = self.module.NormalDist
  2211. data = [96, 107, 90, 92, 110]
  2212. # list input
  2213. self.assertEqual(NormalDist.from_samples(data), NormalDist(99, 9))
  2214. # tuple input
  2215. self.assertEqual(NormalDist.from_samples(tuple(data)), NormalDist(99, 9))
  2216. # iterator input
  2217. self.assertEqual(NormalDist.from_samples(iter(data)), NormalDist(99, 9))
  2218. # error cases
  2219. with self.assertRaises(self.module.StatisticsError):
  2220. NormalDist.from_samples([]) # empty input
  2221. with self.assertRaises(self.module.StatisticsError):
  2222. NormalDist.from_samples([10]) # only one input
  2223. # verify that subclass type is honored
  2224. class NewNormalDist(NormalDist):
  2225. pass
  2226. nnd = NewNormalDist.from_samples(data)
  2227. self.assertEqual(type(nnd), NewNormalDist)
  2228. def test_sample_generation(self):
  2229. NormalDist = self.module.NormalDist
  2230. mu, sigma = 10_000, 3.0
  2231. X = NormalDist(mu, sigma)
  2232. n = 1_000
  2233. data = X.samples(n)
  2234. self.assertEqual(len(data), n)
  2235. self.assertEqual(set(map(type, data)), {float})
  2236. # mean(data) expected to fall within 8 standard deviations
  2237. xbar = self.module.mean(data)
  2238. self.assertTrue(mu - sigma*8 <= xbar <= mu + sigma*8)
  2239. # verify that seeding makes reproducible sequences
  2240. n = 100
  2241. data1 = X.samples(n, seed='happiness and joy')
  2242. data2 = X.samples(n, seed='trouble and despair')
  2243. data3 = X.samples(n, seed='happiness and joy')
  2244. data4 = X.samples(n, seed='trouble and despair')
  2245. self.assertEqual(data1, data3)
  2246. self.assertEqual(data2, data4)
  2247. self.assertNotEqual(data1, data2)
  2248. def test_pdf(self):
  2249. NormalDist = self.module.NormalDist
  2250. X = NormalDist(100, 15)
  2251. # Verify peak around center
  2252. self.assertLess(X.pdf(99), X.pdf(100))
  2253. self.assertLess(X.pdf(101), X.pdf(100))
  2254. # Test symmetry
  2255. for i in range(50):
  2256. self.assertAlmostEqual(X.pdf(100 - i), X.pdf(100 + i))
  2257. # Test vs CDF
  2258. dx = 2.0 ** -10
  2259. for x in range(90, 111):
  2260. est_pdf = (X.cdf(x + dx) - X.cdf(x)) / dx
  2261. self.assertAlmostEqual(X.pdf(x), est_pdf, places=4)
  2262. # Test vs table of known values -- CRC 26th Edition
  2263. Z = NormalDist()
  2264. for x, px in enumerate([
  2265. 0.3989, 0.3989, 0.3989, 0.3988, 0.3986,
  2266. 0.3984, 0.3982, 0.3980, 0.3977, 0.3973,
  2267. 0.3970, 0.3965, 0.3961, 0.3956, 0.3951,
  2268. 0.3945, 0.3939, 0.3932, 0.3925, 0.3918,
  2269. 0.3910, 0.3902, 0.3894, 0.3885, 0.3876,
  2270. 0.3867, 0.3857, 0.3847, 0.3836, 0.3825,
  2271. 0.3814, 0.3802, 0.3790, 0.3778, 0.3765,
  2272. 0.3752, 0.3739, 0.3725, 0.3712, 0.3697,
  2273. 0.3683, 0.3668, 0.3653, 0.3637, 0.3621,
  2274. 0.3605, 0.3589, 0.3572, 0.3555, 0.3538,
  2275. ]):
  2276. self.assertAlmostEqual(Z.pdf(x / 100.0), px, places=4)
  2277. self.assertAlmostEqual(Z.pdf(-x / 100.0), px, places=4)
  2278. # Error case: variance is zero
  2279. Y = NormalDist(100, 0)
  2280. with self.assertRaises(self.module.StatisticsError):
  2281. Y.pdf(90)
  2282. # Special values
  2283. self.assertEqual(X.pdf(float('-Inf')), 0.0)
  2284. self.assertEqual(X.pdf(float('Inf')), 0.0)
  2285. self.assertTrue(math.isnan(X.pdf(float('NaN'))))
  2286. def test_cdf(self):
  2287. NormalDist = self.module.NormalDist
  2288. X = NormalDist(100, 15)
  2289. cdfs = [X.cdf(x) for x in range(1, 200)]
  2290. self.assertEqual(set(map(type, cdfs)), {float})
  2291. # Verify montonic
  2292. self.assertEqual(cdfs, sorted(cdfs))
  2293. # Verify center (should be exact)
  2294. self.assertEqual(X.cdf(100), 0.50)
  2295. # Check against a table of known values
  2296. # https://en.wikipedia.org/wiki/Standard_normal_table#Cumulative
  2297. Z = NormalDist()
  2298. for z, cum_prob in [
  2299. (0.00, 0.50000), (0.01, 0.50399), (0.02, 0.50798),
  2300. (0.14, 0.55567), (0.29, 0.61409), (0.33, 0.62930),
  2301. (0.54, 0.70540), (0.60, 0.72575), (1.17, 0.87900),
  2302. (1.60, 0.94520), (2.05, 0.97982), (2.89, 0.99807),
  2303. (3.52, 0.99978), (3.98, 0.99997), (4.07, 0.99998),
  2304. ]:
  2305. self.assertAlmostEqual(Z.cdf(z), cum_prob, places=5)
  2306. self.assertAlmostEqual(Z.cdf(-z), 1.0 - cum_prob, places=5)
  2307. # Error case: variance is zero
  2308. Y = NormalDist(100, 0)
  2309. with self.assertRaises(self.module.StatisticsError):
  2310. Y.cdf(90)
  2311. # Special values
  2312. self.assertEqual(X.cdf(float('-Inf')), 0.0)
  2313. self.assertEqual(X.cdf(float('Inf')), 1.0)
  2314. self.assertTrue(math.isnan(X.cdf(float('NaN'))))
  2315. @support.skip_if_pgo_task
  2316. def test_inv_cdf(self):
  2317. NormalDist = self.module.NormalDist
  2318. # Center case should be exact.
  2319. iq = NormalDist(100, 15)
  2320. self.assertEqual(iq.inv_cdf(0.50), iq.mean)
  2321. # Test versus a published table of known percentage points.
  2322. # See the second table at the bottom of the page here:
  2323. # http://people.bath.ac.uk/masss/tables/normaltable.pdf
  2324. Z = NormalDist()
  2325. pp = {5.0: (0.000, 1.645, 2.576, 3.291, 3.891,
  2326. 4.417, 4.892, 5.327, 5.731, 6.109),
  2327. 2.5: (0.674, 1.960, 2.807, 3.481, 4.056,
  2328. 4.565, 5.026, 5.451, 5.847, 6.219),
  2329. 1.0: (1.282, 2.326, 3.090, 3.719, 4.265,
  2330. 4.753, 5.199, 5.612, 5.998, 6.361)}
  2331. for base, row in pp.items():
  2332. for exp, x in enumerate(row, start=1):
  2333. p = base * 10.0 ** (-exp)
  2334. self.assertAlmostEqual(-Z.inv_cdf(p), x, places=3)
  2335. p = 1.0 - p
  2336. self.assertAlmostEqual(Z.inv_cdf(p), x, places=3)
  2337. # Match published example for MS Excel
  2338. # https://support.office.com/en-us/article/norm-inv-function-54b30935-fee7-493c-bedb-2278a9db7e13
  2339. self.assertAlmostEqual(NormalDist(40, 1.5).inv_cdf(0.908789), 42.000002)
  2340. # One million equally spaced probabilities
  2341. n = 2**20
  2342. for p in range(1, n):
  2343. p /= n
  2344. self.assertAlmostEqual(iq.cdf(iq.inv_cdf(p)), p)
  2345. # One hundred ever smaller probabilities to test tails out to
  2346. # extreme probabilities: 1 / 2**50 and (2**50-1) / 2 ** 50
  2347. for e in range(1, 51):
  2348. p = 2.0 ** (-e)
  2349. self.assertAlmostEqual(iq.cdf(iq.inv_cdf(p)), p)
  2350. p = 1.0 - p
  2351. self.assertAlmostEqual(iq.cdf(iq.inv_cdf(p)), p)
  2352. # Now apply cdf() first. Near the tails, the round-trip loses
  2353. # precision and is ill-conditioned (small changes in the inputs
  2354. # give large changes in the output), so only check to 5 places.
  2355. for x in range(200):
  2356. self.assertAlmostEqual(iq.inv_cdf(iq.cdf(x)), x, places=5)
  2357. # Error cases:
  2358. with self.assertRaises(self.module.StatisticsError):
  2359. iq.inv_cdf(0.0) # p is zero
  2360. with self.assertRaises(self.module.StatisticsError):
  2361. iq.inv_cdf(-0.1) # p under zero
  2362. with self.assertRaises(self.module.StatisticsError):
  2363. iq.inv_cdf(1.0) # p is one
  2364. with self.assertRaises(self.module.StatisticsError):
  2365. iq.inv_cdf(1.1) # p over one
  2366. with self.assertRaises(self.module.StatisticsError):
  2367. iq = NormalDist(100, 0) # sigma is zero
  2368. iq.inv_cdf(0.5)
  2369. # Special values
  2370. self.assertTrue(math.isnan(Z.inv_cdf(float('NaN'))))
  2371. def test_quantiles(self):
  2372. # Quartiles of a standard normal distribution
  2373. Z = self.module.NormalDist()
  2374. for n, expected in [
  2375. (1, []),
  2376. (2, [0.0]),
  2377. (3, [-0.4307, 0.4307]),
  2378. (4 ,[-0.6745, 0.0, 0.6745]),
  2379. ]:
  2380. actual = Z.quantiles(n=n)
  2381. self.assertTrue(all(math.isclose(e, a, abs_tol=0.0001)
  2382. for e, a in zip(expected, actual)))
  2383. def test_overlap(self):
  2384. NormalDist = self.module.NormalDist
  2385. # Match examples from Imman and Bradley
  2386. for X1, X2, published_result in [
  2387. (NormalDist(0.0, 2.0), NormalDist(1.0, 2.0), 0.80258),
  2388. (NormalDist(0.0, 1.0), NormalDist(1.0, 2.0), 0.60993),
  2389. ]:
  2390. self.assertAlmostEqual(X1.overlap(X2), published_result, places=4)
  2391. self.assertAlmostEqual(X2.overlap(X1), published_result, places=4)
  2392. # Check against integration of the PDF
  2393. def overlap_numeric(X, Y, *, steps=8_192, z=5):
  2394. 'Numerical integration cross-check for overlap() '
  2395. fsum = math.fsum
  2396. center = (X.mean + Y.mean) / 2.0
  2397. width = z * max(X.stdev, Y.stdev)
  2398. start = center - width
  2399. dx = 2.0 * width / steps
  2400. x_arr = [start + i*dx for i in range(steps)]
  2401. xp = list(map(X.pdf, x_arr))
  2402. yp = list(map(Y.pdf, x_arr))
  2403. total = max(fsum(xp), fsum(yp))
  2404. return fsum(map(min, xp, yp)) / total
  2405. for X1, X2 in [
  2406. # Examples from Imman and Bradley
  2407. (NormalDist(0.0, 2.0), NormalDist(1.0, 2.0)),
  2408. (NormalDist(0.0, 1.0), NormalDist(1.0, 2.0)),
  2409. # Example from https://www.rasch.org/rmt/rmt101r.htm
  2410. (NormalDist(0.0, 1.0), NormalDist(1.0, 2.0)),
  2411. # Gender heights from http://www.usablestats.com/lessons/normal
  2412. (NormalDist(70, 4), NormalDist(65, 3.5)),
  2413. # Misc cases with equal standard deviations
  2414. (NormalDist(100, 15), NormalDist(110, 15)),
  2415. (NormalDist(-100, 15), NormalDist(110, 15)),
  2416. (NormalDist(-100, 15), NormalDist(-110, 15)),
  2417. # Misc cases with unequal standard deviations
  2418. (NormalDist(100, 12), NormalDist(100, 15)),
  2419. (NormalDist(100, 12), NormalDist(110, 15)),
  2420. (NormalDist(100, 12), NormalDist(150, 15)),
  2421. (NormalDist(100, 12), NormalDist(150, 35)),
  2422. # Misc cases with small values
  2423. (NormalDist(1.000, 0.002), NormalDist(1.001, 0.003)),
  2424. (NormalDist(1.000, 0.002), NormalDist(1.006, 0.0003)),
  2425. (NormalDist(1.000, 0.002), NormalDist(1.001, 0.099)),
  2426. ]:
  2427. self.assertAlmostEqual(X1.overlap(X2), overlap_numeric(X1, X2), places=5)
  2428. self.assertAlmostEqual(X2.overlap(X1), overlap_numeric(X1, X2), places=5)
  2429. # Error cases
  2430. X = NormalDist()
  2431. with self.assertRaises(TypeError):
  2432. X.overlap() # too few arguments
  2433. with self.assertRaises(TypeError):
  2434. X.overlap(X, X) # too may arguments
  2435. with self.assertRaises(TypeError):
  2436. X.overlap(None) # right operand not a NormalDist
  2437. with self.assertRaises(self.module.StatisticsError):
  2438. X.overlap(NormalDist(1, 0)) # right operand sigma is zero
  2439. with self.assertRaises(self.module.StatisticsError):
  2440. NormalDist(1, 0).overlap(X) # left operand sigma is zero
  2441. def test_zscore(self):
  2442. NormalDist = self.module.NormalDist
  2443. X = NormalDist(100, 15)
  2444. self.assertEqual(X.zscore(142), 2.8)
  2445. self.assertEqual(X.zscore(58), -2.8)
  2446. self.assertEqual(X.zscore(100), 0.0)
  2447. with self.assertRaises(TypeError):
  2448. X.zscore() # too few arguments
  2449. with self.assertRaises(TypeError):
  2450. X.zscore(1, 1) # too may arguments
  2451. with self.assertRaises(TypeError):
  2452. X.zscore(None) # non-numeric type
  2453. with self.assertRaises(self.module.StatisticsError):
  2454. NormalDist(1, 0).zscore(100) # sigma is zero
  2455. def test_properties(self):
  2456. X = self.module.NormalDist(100, 15)
  2457. self.assertEqual(X.mean, 100)
  2458. self.assertEqual(X.median, 100)
  2459. self.assertEqual(X.mode, 100)
  2460. self.assertEqual(X.stdev, 15)
  2461. self.assertEqual(X.variance, 225)
  2462. def test_same_type_addition_and_subtraction(self):
  2463. NormalDist = self.module.NormalDist
  2464. X = NormalDist(100, 12)
  2465. Y = NormalDist(40, 5)
  2466. self.assertEqual(X + Y, NormalDist(140, 13)) # __add__
  2467. self.assertEqual(X - Y, NormalDist(60, 13)) # __sub__
  2468. def test_translation_and_scaling(self):
  2469. NormalDist = self.module.NormalDist
  2470. X = NormalDist(100, 15)
  2471. y = 10
  2472. self.assertEqual(+X, NormalDist(100, 15)) # __pos__
  2473. self.assertEqual(-X, NormalDist(-100, 15)) # __neg__
  2474. self.assertEqual(X + y, NormalDist(110, 15)) # __add__
  2475. self.assertEqual(y + X, NormalDist(110, 15)) # __radd__
  2476. self.assertEqual(X - y, NormalDist(90, 15)) # __sub__
  2477. self.assertEqual(y - X, NormalDist(-90, 15)) # __rsub__
  2478. self.assertEqual(X * y, NormalDist(1000, 150)) # __mul__
  2479. self.assertEqual(y * X, NormalDist(1000, 150)) # __rmul__
  2480. self.assertEqual(X / y, NormalDist(10, 1.5)) # __truediv__
  2481. with self.assertRaises(TypeError): # __rtruediv__
  2482. y / X
  2483. def test_unary_operations(self):
  2484. NormalDist = self.module.NormalDist
  2485. X = NormalDist(100, 12)
  2486. Y = +X
  2487. self.assertIsNot(X, Y)
  2488. self.assertEqual(X.mean, Y.mean)
  2489. self.assertEqual(X.stdev, Y.stdev)
  2490. Y = -X
  2491. self.assertIsNot(X, Y)
  2492. self.assertEqual(X.mean, -Y.mean)
  2493. self.assertEqual(X.stdev, Y.stdev)
  2494. def test_equality(self):
  2495. NormalDist = self.module.NormalDist
  2496. nd1 = NormalDist()
  2497. nd2 = NormalDist(2, 4)
  2498. nd3 = NormalDist()
  2499. nd4 = NormalDist(2, 4)
  2500. nd5 = NormalDist(2, 8)
  2501. nd6 = NormalDist(8, 4)
  2502. self.assertNotEqual(nd1, nd2)
  2503. self.assertEqual(nd1, nd3)
  2504. self.assertEqual(nd2, nd4)
  2505. self.assertNotEqual(nd2, nd5)
  2506. self.assertNotEqual(nd2, nd6)
  2507. # Test NotImplemented when types are different
  2508. class A:
  2509. def __eq__(self, other):
  2510. return 10
  2511. a = A()
  2512. self.assertEqual(nd1.__eq__(a), NotImplemented)
  2513. self.assertEqual(nd1 == a, 10)
  2514. self.assertEqual(a == nd1, 10)
  2515. # All subclasses to compare equal giving the same behavior
  2516. # as list, tuple, int, float, complex, str, dict, set, etc.
  2517. class SizedNormalDist(NormalDist):
  2518. def __init__(self, mu, sigma, n):
  2519. super().__init__(mu, sigma)
  2520. self.n = n
  2521. s = SizedNormalDist(100, 15, 57)
  2522. nd4 = NormalDist(100, 15)
  2523. self.assertEqual(s, nd4)
  2524. # Don't allow duck type equality because we wouldn't
  2525. # want a lognormal distribution to compare equal
  2526. # to a normal distribution with the same parameters
  2527. class LognormalDist:
  2528. def __init__(self, mu, sigma):
  2529. self.mu = mu
  2530. self.sigma = sigma
  2531. lnd = LognormalDist(100, 15)
  2532. nd = NormalDist(100, 15)
  2533. self.assertNotEqual(nd, lnd)
  2534. def test_copy(self):
  2535. nd = self.module.NormalDist(37.5, 5.625)
  2536. nd1 = copy.copy(nd)
  2537. self.assertEqual(nd, nd1)
  2538. nd2 = copy.deepcopy(nd)
  2539. self.assertEqual(nd, nd2)
  2540. def test_pickle(self):
  2541. nd = self.module.NormalDist(37.5, 5.625)
  2542. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  2543. with self.subTest(proto=proto):
  2544. pickled = pickle.loads(pickle.dumps(nd, protocol=proto))
  2545. self.assertEqual(nd, pickled)
  2546. def test_hashability(self):
  2547. ND = self.module.NormalDist
  2548. s = {ND(100, 15), ND(100.0, 15.0), ND(100, 10), ND(95, 15), ND(100, 15)}
  2549. self.assertEqual(len(s), 3)
  2550. def test_repr(self):
  2551. nd = self.module.NormalDist(37.5, 5.625)
  2552. self.assertEqual(repr(nd), 'NormalDist(mu=37.5, sigma=5.625)')
  2553. # Swapping the sys.modules['statistics'] is to solving the
  2554. # _pickle.PicklingError:
  2555. # Can't pickle <class 'statistics.NormalDist'>:
  2556. # it's not the same object as statistics.NormalDist
  2557. class TestNormalDistPython(unittest.TestCase, TestNormalDist):
  2558. module = py_statistics
  2559. def setUp(self):
  2560. sys.modules['statistics'] = self.module
  2561. def tearDown(self):
  2562. sys.modules['statistics'] = statistics
  2563. @unittest.skipUnless(c_statistics, 'requires _statistics')
  2564. class TestNormalDistC(unittest.TestCase, TestNormalDist):
  2565. module = c_statistics
  2566. def setUp(self):
  2567. sys.modules['statistics'] = self.module
  2568. def tearDown(self):
  2569. sys.modules['statistics'] = statistics
  2570. # === Run tests ===
  2571. def load_tests(loader, tests, ignore):
  2572. """Used for doctest/unittest integration."""
  2573. tests.addTests(doctest.DocTestSuite())
  2574. return tests
  2575. if __name__ == "__main__":
  2576. unittest.main()