test_random.py 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751
  1. import warnings
  2. import pytest
  3. import numpy as np
  4. from numpy.testing import (
  5. assert_, assert_raises, assert_equal, assert_warns,
  6. assert_no_warnings, assert_array_equal, assert_array_almost_equal,
  7. suppress_warnings, IS_WASM
  8. )
  9. from numpy import random
  10. import sys
  11. class TestSeed:
  12. def test_scalar(self):
  13. s = np.random.RandomState(0)
  14. assert_equal(s.randint(1000), 684)
  15. s = np.random.RandomState(4294967295)
  16. assert_equal(s.randint(1000), 419)
  17. def test_array(self):
  18. s = np.random.RandomState(range(10))
  19. assert_equal(s.randint(1000), 468)
  20. s = np.random.RandomState(np.arange(10))
  21. assert_equal(s.randint(1000), 468)
  22. s = np.random.RandomState([0])
  23. assert_equal(s.randint(1000), 973)
  24. s = np.random.RandomState([4294967295])
  25. assert_equal(s.randint(1000), 265)
  26. def test_invalid_scalar(self):
  27. # seed must be an unsigned 32 bit integer
  28. assert_raises(TypeError, np.random.RandomState, -0.5)
  29. assert_raises(ValueError, np.random.RandomState, -1)
  30. def test_invalid_array(self):
  31. # seed must be an unsigned 32 bit integer
  32. assert_raises(TypeError, np.random.RandomState, [-0.5])
  33. assert_raises(ValueError, np.random.RandomState, [-1])
  34. assert_raises(ValueError, np.random.RandomState, [4294967296])
  35. assert_raises(ValueError, np.random.RandomState, [1, 2, 4294967296])
  36. assert_raises(ValueError, np.random.RandomState, [1, -2, 4294967296])
  37. def test_invalid_array_shape(self):
  38. # gh-9832
  39. assert_raises(ValueError, np.random.RandomState,
  40. np.array([], dtype=np.int64))
  41. assert_raises(ValueError, np.random.RandomState, [[1, 2, 3]])
  42. assert_raises(ValueError, np.random.RandomState, [[1, 2, 3],
  43. [4, 5, 6]])
  44. class TestBinomial:
  45. def test_n_zero(self):
  46. # Tests the corner case of n == 0 for the binomial distribution.
  47. # binomial(0, p) should be zero for any p in [0, 1].
  48. # This test addresses issue #3480.
  49. zeros = np.zeros(2, dtype='int')
  50. for p in [0, .5, 1]:
  51. assert_(random.binomial(0, p) == 0)
  52. assert_array_equal(random.binomial(zeros, p), zeros)
  53. def test_p_is_nan(self):
  54. # Issue #4571.
  55. assert_raises(ValueError, random.binomial, 1, np.nan)
  56. class TestMultinomial:
  57. def test_basic(self):
  58. random.multinomial(100, [0.2, 0.8])
  59. def test_zero_probability(self):
  60. random.multinomial(100, [0.2, 0.8, 0.0, 0.0, 0.0])
  61. def test_int_negative_interval(self):
  62. assert_(-5 <= random.randint(-5, -1) < -1)
  63. x = random.randint(-5, -1, 5)
  64. assert_(np.all(-5 <= x))
  65. assert_(np.all(x < -1))
  66. def test_size(self):
  67. # gh-3173
  68. p = [0.5, 0.5]
  69. assert_equal(np.random.multinomial(1, p, np.uint32(1)).shape, (1, 2))
  70. assert_equal(np.random.multinomial(1, p, np.uint32(1)).shape, (1, 2))
  71. assert_equal(np.random.multinomial(1, p, np.uint32(1)).shape, (1, 2))
  72. assert_equal(np.random.multinomial(1, p, [2, 2]).shape, (2, 2, 2))
  73. assert_equal(np.random.multinomial(1, p, (2, 2)).shape, (2, 2, 2))
  74. assert_equal(np.random.multinomial(1, p, np.array((2, 2))).shape,
  75. (2, 2, 2))
  76. assert_raises(TypeError, np.random.multinomial, 1, p,
  77. float(1))
  78. def test_multidimensional_pvals(self):
  79. assert_raises(ValueError, np.random.multinomial, 10, [[0, 1]])
  80. assert_raises(ValueError, np.random.multinomial, 10, [[0], [1]])
  81. assert_raises(ValueError, np.random.multinomial, 10, [[[0], [1]], [[1], [0]]])
  82. assert_raises(ValueError, np.random.multinomial, 10, np.array([[0, 1], [1, 0]]))
  83. class TestSetState:
  84. def setup_method(self):
  85. self.seed = 1234567890
  86. self.prng = random.RandomState(self.seed)
  87. self.state = self.prng.get_state()
  88. def test_basic(self):
  89. old = self.prng.tomaxint(16)
  90. self.prng.set_state(self.state)
  91. new = self.prng.tomaxint(16)
  92. assert_(np.all(old == new))
  93. def test_gaussian_reset(self):
  94. # Make sure the cached every-other-Gaussian is reset.
  95. old = self.prng.standard_normal(size=3)
  96. self.prng.set_state(self.state)
  97. new = self.prng.standard_normal(size=3)
  98. assert_(np.all(old == new))
  99. def test_gaussian_reset_in_media_res(self):
  100. # When the state is saved with a cached Gaussian, make sure the
  101. # cached Gaussian is restored.
  102. self.prng.standard_normal()
  103. state = self.prng.get_state()
  104. old = self.prng.standard_normal(size=3)
  105. self.prng.set_state(state)
  106. new = self.prng.standard_normal(size=3)
  107. assert_(np.all(old == new))
  108. def test_backwards_compatibility(self):
  109. # Make sure we can accept old state tuples that do not have the
  110. # cached Gaussian value.
  111. old_state = self.state[:-2]
  112. x1 = self.prng.standard_normal(size=16)
  113. self.prng.set_state(old_state)
  114. x2 = self.prng.standard_normal(size=16)
  115. self.prng.set_state(self.state)
  116. x3 = self.prng.standard_normal(size=16)
  117. assert_(np.all(x1 == x2))
  118. assert_(np.all(x1 == x3))
  119. def test_negative_binomial(self):
  120. # Ensure that the negative binomial results take floating point
  121. # arguments without truncation.
  122. self.prng.negative_binomial(0.5, 0.5)
  123. def test_set_invalid_state(self):
  124. # gh-25402
  125. with pytest.raises(IndexError):
  126. self.prng.set_state(())
  127. class TestRandint:
  128. rfunc = np.random.randint
  129. # valid integer/boolean types
  130. itype = [np.bool, np.int8, np.uint8, np.int16, np.uint16,
  131. np.int32, np.uint32, np.int64, np.uint64]
  132. def test_unsupported_type(self):
  133. assert_raises(TypeError, self.rfunc, 1, dtype=float)
  134. def test_bounds_checking(self):
  135. for dt in self.itype:
  136. lbnd = 0 if dt is np.bool else np.iinfo(dt).min
  137. ubnd = 2 if dt is np.bool else np.iinfo(dt).max + 1
  138. assert_raises(ValueError, self.rfunc, lbnd - 1, ubnd, dtype=dt)
  139. assert_raises(ValueError, self.rfunc, lbnd, ubnd + 1, dtype=dt)
  140. assert_raises(ValueError, self.rfunc, ubnd, lbnd, dtype=dt)
  141. assert_raises(ValueError, self.rfunc, 1, 0, dtype=dt)
  142. def test_rng_zero_and_extremes(self):
  143. for dt in self.itype:
  144. lbnd = 0 if dt is np.bool else np.iinfo(dt).min
  145. ubnd = 2 if dt is np.bool else np.iinfo(dt).max + 1
  146. tgt = ubnd - 1
  147. assert_equal(self.rfunc(tgt, tgt + 1, size=1000, dtype=dt), tgt)
  148. tgt = lbnd
  149. assert_equal(self.rfunc(tgt, tgt + 1, size=1000, dtype=dt), tgt)
  150. tgt = (lbnd + ubnd)//2
  151. assert_equal(self.rfunc(tgt, tgt + 1, size=1000, dtype=dt), tgt)
  152. def test_full_range(self):
  153. # Test for ticket #1690
  154. for dt in self.itype:
  155. lbnd = 0 if dt is np.bool else np.iinfo(dt).min
  156. ubnd = 2 if dt is np.bool else np.iinfo(dt).max + 1
  157. try:
  158. self.rfunc(lbnd, ubnd, dtype=dt)
  159. except Exception as e:
  160. raise AssertionError("No error should have been raised, "
  161. "but one was with the following "
  162. "message:\n\n%s" % str(e))
  163. def test_in_bounds_fuzz(self):
  164. # Don't use fixed seed
  165. np.random.seed()
  166. for dt in self.itype[1:]:
  167. for ubnd in [4, 8, 16]:
  168. vals = self.rfunc(2, ubnd, size=2**16, dtype=dt)
  169. assert_(vals.max() < ubnd)
  170. assert_(vals.min() >= 2)
  171. vals = self.rfunc(0, 2, size=2**16, dtype=np.bool)
  172. assert_(vals.max() < 2)
  173. assert_(vals.min() >= 0)
  174. def test_repeatability(self):
  175. import hashlib
  176. # We use a sha256 hash of generated sequences of 1000 samples
  177. # in the range [0, 6) for all but bool, where the range
  178. # is [0, 2). Hashes are for little endian numbers.
  179. tgt = {'bool': '509aea74d792fb931784c4b0135392c65aec64beee12b0cc167548a2c3d31e71',
  180. 'int16': '7b07f1a920e46f6d0fe02314155a2330bcfd7635e708da50e536c5ebb631a7d4',
  181. 'int32': 'e577bfed6c935de944424667e3da285012e741892dcb7051a8f1ce68ab05c92f',
  182. 'int64': '0fbead0b06759df2cfb55e43148822d4a1ff953c7eb19a5b08445a63bb64fa9e',
  183. 'int8': '001aac3a5acb935a9b186cbe14a1ca064b8bb2dd0b045d48abeacf74d0203404',
  184. 'uint16': '7b07f1a920e46f6d0fe02314155a2330bcfd7635e708da50e536c5ebb631a7d4',
  185. 'uint32': 'e577bfed6c935de944424667e3da285012e741892dcb7051a8f1ce68ab05c92f',
  186. 'uint64': '0fbead0b06759df2cfb55e43148822d4a1ff953c7eb19a5b08445a63bb64fa9e',
  187. 'uint8': '001aac3a5acb935a9b186cbe14a1ca064b8bb2dd0b045d48abeacf74d0203404'}
  188. for dt in self.itype[1:]:
  189. np.random.seed(1234)
  190. # view as little endian for hash
  191. if sys.byteorder == 'little':
  192. val = self.rfunc(0, 6, size=1000, dtype=dt)
  193. else:
  194. val = self.rfunc(0, 6, size=1000, dtype=dt).byteswap()
  195. res = hashlib.sha256(val.view(np.int8)).hexdigest()
  196. assert_(tgt[np.dtype(dt).name] == res)
  197. # bools do not depend on endianness
  198. np.random.seed(1234)
  199. val = self.rfunc(0, 2, size=1000, dtype=bool).view(np.int8)
  200. res = hashlib.sha256(val).hexdigest()
  201. assert_(tgt[np.dtype(bool).name] == res)
  202. def test_int64_uint64_corner_case(self):
  203. # When stored in Numpy arrays, `lbnd` is casted
  204. # as np.int64, and `ubnd` is casted as np.uint64.
  205. # Checking whether `lbnd` >= `ubnd` used to be
  206. # done solely via direct comparison, which is incorrect
  207. # because when Numpy tries to compare both numbers,
  208. # it casts both to np.float64 because there is
  209. # no integer superset of np.int64 and np.uint64. However,
  210. # `ubnd` is too large to be represented in np.float64,
  211. # causing it be round down to np.iinfo(np.int64).max,
  212. # leading to a ValueError because `lbnd` now equals
  213. # the new `ubnd`.
  214. dt = np.int64
  215. tgt = np.iinfo(np.int64).max
  216. lbnd = np.int64(np.iinfo(np.int64).max)
  217. ubnd = np.uint64(np.iinfo(np.int64).max + 1)
  218. # None of these function calls should
  219. # generate a ValueError now.
  220. actual = np.random.randint(lbnd, ubnd, dtype=dt)
  221. assert_equal(actual, tgt)
  222. def test_respect_dtype_singleton(self):
  223. # See gh-7203
  224. for dt in self.itype:
  225. lbnd = 0 if dt is np.bool else np.iinfo(dt).min
  226. ubnd = 2 if dt is np.bool else np.iinfo(dt).max + 1
  227. sample = self.rfunc(lbnd, ubnd, dtype=dt)
  228. assert_equal(sample.dtype, np.dtype(dt))
  229. for dt in (bool, int):
  230. # The legacy rng uses "long" as the default integer:
  231. lbnd = 0 if dt is bool else np.iinfo("long").min
  232. ubnd = 2 if dt is bool else np.iinfo("long").max + 1
  233. # gh-7284: Ensure that we get Python data types
  234. sample = self.rfunc(lbnd, ubnd, dtype=dt)
  235. assert_(not hasattr(sample, 'dtype'))
  236. assert_equal(type(sample), dt)
  237. class TestRandomDist:
  238. # Make sure the random distribution returns the correct value for a
  239. # given seed
  240. def setup_method(self):
  241. self.seed = 1234567890
  242. def test_rand(self):
  243. np.random.seed(self.seed)
  244. actual = np.random.rand(3, 2)
  245. desired = np.array([[0.61879477158567997, 0.59162362775974664],
  246. [0.88868358904449662, 0.89165480011560816],
  247. [0.4575674820298663, 0.7781880808593471]])
  248. assert_array_almost_equal(actual, desired, decimal=15)
  249. def test_randn(self):
  250. np.random.seed(self.seed)
  251. actual = np.random.randn(3, 2)
  252. desired = np.array([[1.34016345771863121, 1.73759122771936081],
  253. [1.498988344300628, -0.2286433324536169],
  254. [2.031033998682787, 2.17032494605655257]])
  255. assert_array_almost_equal(actual, desired, decimal=15)
  256. def test_randint(self):
  257. np.random.seed(self.seed)
  258. actual = np.random.randint(-99, 99, size=(3, 2))
  259. desired = np.array([[31, 3],
  260. [-52, 41],
  261. [-48, -66]])
  262. assert_array_equal(actual, desired)
  263. def test_random_integers(self):
  264. np.random.seed(self.seed)
  265. with suppress_warnings() as sup:
  266. w = sup.record(DeprecationWarning)
  267. actual = np.random.random_integers(-99, 99, size=(3, 2))
  268. assert_(len(w) == 1)
  269. desired = np.array([[31, 3],
  270. [-52, 41],
  271. [-48, -66]])
  272. assert_array_equal(actual, desired)
  273. def test_random_integers_max_int(self):
  274. # Tests whether random_integers can generate the
  275. # maximum allowed Python int that can be converted
  276. # into a C long. Previous implementations of this
  277. # method have thrown an OverflowError when attempting
  278. # to generate this integer.
  279. with suppress_warnings() as sup:
  280. w = sup.record(DeprecationWarning)
  281. actual = np.random.random_integers(np.iinfo('l').max,
  282. np.iinfo('l').max)
  283. assert_(len(w) == 1)
  284. desired = np.iinfo('l').max
  285. assert_equal(actual, desired)
  286. def test_random_integers_deprecated(self):
  287. with warnings.catch_warnings():
  288. warnings.simplefilter("error", DeprecationWarning)
  289. # DeprecationWarning raised with high == None
  290. assert_raises(DeprecationWarning,
  291. np.random.random_integers,
  292. np.iinfo('l').max)
  293. # DeprecationWarning raised with high != None
  294. assert_raises(DeprecationWarning,
  295. np.random.random_integers,
  296. np.iinfo('l').max, np.iinfo('l').max)
  297. def test_random(self):
  298. np.random.seed(self.seed)
  299. actual = np.random.random((3, 2))
  300. desired = np.array([[0.61879477158567997, 0.59162362775974664],
  301. [0.88868358904449662, 0.89165480011560816],
  302. [0.4575674820298663, 0.7781880808593471]])
  303. assert_array_almost_equal(actual, desired, decimal=15)
  304. def test_choice_uniform_replace(self):
  305. np.random.seed(self.seed)
  306. actual = np.random.choice(4, 4)
  307. desired = np.array([2, 3, 2, 3])
  308. assert_array_equal(actual, desired)
  309. def test_choice_nonuniform_replace(self):
  310. np.random.seed(self.seed)
  311. actual = np.random.choice(4, 4, p=[0.4, 0.4, 0.1, 0.1])
  312. desired = np.array([1, 1, 2, 2])
  313. assert_array_equal(actual, desired)
  314. def test_choice_uniform_noreplace(self):
  315. np.random.seed(self.seed)
  316. actual = np.random.choice(4, 3, replace=False)
  317. desired = np.array([0, 1, 3])
  318. assert_array_equal(actual, desired)
  319. def test_choice_nonuniform_noreplace(self):
  320. np.random.seed(self.seed)
  321. actual = np.random.choice(4, 3, replace=False,
  322. p=[0.1, 0.3, 0.5, 0.1])
  323. desired = np.array([2, 3, 1])
  324. assert_array_equal(actual, desired)
  325. def test_choice_noninteger(self):
  326. np.random.seed(self.seed)
  327. actual = np.random.choice(['a', 'b', 'c', 'd'], 4)
  328. desired = np.array(['c', 'd', 'c', 'd'])
  329. assert_array_equal(actual, desired)
  330. def test_choice_exceptions(self):
  331. sample = np.random.choice
  332. assert_raises(ValueError, sample, -1, 3)
  333. assert_raises(ValueError, sample, 3., 3)
  334. assert_raises(ValueError, sample, [[1, 2], [3, 4]], 3)
  335. assert_raises(ValueError, sample, [], 3)
  336. assert_raises(ValueError, sample, [1, 2, 3, 4], 3,
  337. p=[[0.25, 0.25], [0.25, 0.25]])
  338. assert_raises(ValueError, sample, [1, 2], 3, p=[0.4, 0.4, 0.2])
  339. assert_raises(ValueError, sample, [1, 2], 3, p=[1.1, -0.1])
  340. assert_raises(ValueError, sample, [1, 2], 3, p=[0.4, 0.4])
  341. assert_raises(ValueError, sample, [1, 2, 3], 4, replace=False)
  342. # gh-13087
  343. assert_raises(ValueError, sample, [1, 2, 3], -2, replace=False)
  344. assert_raises(ValueError, sample, [1, 2, 3], (-1,), replace=False)
  345. assert_raises(ValueError, sample, [1, 2, 3], (-1, 1), replace=False)
  346. assert_raises(ValueError, sample, [1, 2, 3], 2,
  347. replace=False, p=[1, 0, 0])
  348. def test_choice_return_shape(self):
  349. p = [0.1, 0.9]
  350. # Check scalar
  351. assert_(np.isscalar(np.random.choice(2, replace=True)))
  352. assert_(np.isscalar(np.random.choice(2, replace=False)))
  353. assert_(np.isscalar(np.random.choice(2, replace=True, p=p)))
  354. assert_(np.isscalar(np.random.choice(2, replace=False, p=p)))
  355. assert_(np.isscalar(np.random.choice([1, 2], replace=True)))
  356. assert_(np.random.choice([None], replace=True) is None)
  357. a = np.array([1, 2])
  358. arr = np.empty(1, dtype=object)
  359. arr[0] = a
  360. assert_(np.random.choice(arr, replace=True) is a)
  361. # Check 0-d array
  362. s = tuple()
  363. assert_(not np.isscalar(np.random.choice(2, s, replace=True)))
  364. assert_(not np.isscalar(np.random.choice(2, s, replace=False)))
  365. assert_(not np.isscalar(np.random.choice(2, s, replace=True, p=p)))
  366. assert_(not np.isscalar(np.random.choice(2, s, replace=False, p=p)))
  367. assert_(not np.isscalar(np.random.choice([1, 2], s, replace=True)))
  368. assert_(np.random.choice([None], s, replace=True).ndim == 0)
  369. a = np.array([1, 2])
  370. arr = np.empty(1, dtype=object)
  371. arr[0] = a
  372. assert_(np.random.choice(arr, s, replace=True).item() is a)
  373. # Check multi dimensional array
  374. s = (2, 3)
  375. p = [0.1, 0.1, 0.1, 0.1, 0.4, 0.2]
  376. assert_equal(np.random.choice(6, s, replace=True).shape, s)
  377. assert_equal(np.random.choice(6, s, replace=False).shape, s)
  378. assert_equal(np.random.choice(6, s, replace=True, p=p).shape, s)
  379. assert_equal(np.random.choice(6, s, replace=False, p=p).shape, s)
  380. assert_equal(np.random.choice(np.arange(6), s, replace=True).shape, s)
  381. # Check zero-size
  382. assert_equal(np.random.randint(0, 0, size=(3, 0, 4)).shape, (3, 0, 4))
  383. assert_equal(np.random.randint(0, -10, size=0).shape, (0,))
  384. assert_equal(np.random.randint(10, 10, size=0).shape, (0,))
  385. assert_equal(np.random.choice(0, size=0).shape, (0,))
  386. assert_equal(np.random.choice([], size=(0,)).shape, (0,))
  387. assert_equal(np.random.choice(['a', 'b'], size=(3, 0, 4)).shape,
  388. (3, 0, 4))
  389. assert_raises(ValueError, np.random.choice, [], 10)
  390. def test_choice_nan_probabilities(self):
  391. a = np.array([42, 1, 2])
  392. p = [None, None, None]
  393. assert_raises(ValueError, np.random.choice, a, p=p)
  394. def test_bytes(self):
  395. np.random.seed(self.seed)
  396. actual = np.random.bytes(10)
  397. desired = b'\x82Ui\x9e\xff\x97+Wf\xa5'
  398. assert_equal(actual, desired)
  399. def test_shuffle(self):
  400. # Test lists, arrays (of various dtypes), and multidimensional versions
  401. # of both, c-contiguous or not:
  402. for conv in [lambda x: np.array([]),
  403. lambda x: x,
  404. lambda x: np.asarray(x).astype(np.int8),
  405. lambda x: np.asarray(x).astype(np.float32),
  406. lambda x: np.asarray(x).astype(np.complex64),
  407. lambda x: np.asarray(x).astype(object),
  408. lambda x: [(i, i) for i in x],
  409. lambda x: np.asarray([[i, i] for i in x]),
  410. lambda x: np.vstack([x, x]).T,
  411. # gh-11442
  412. lambda x: (np.asarray([(i, i) for i in x],
  413. [("a", int), ("b", int)])
  414. .view(np.recarray)),
  415. # gh-4270
  416. lambda x: np.asarray([(i, i) for i in x],
  417. [("a", object), ("b", np.int32)])]:
  418. np.random.seed(self.seed)
  419. alist = conv([1, 2, 3, 4, 5, 6, 7, 8, 9, 0])
  420. np.random.shuffle(alist)
  421. actual = alist
  422. desired = conv([0, 1, 9, 6, 2, 4, 5, 8, 7, 3])
  423. assert_array_equal(actual, desired)
  424. def test_shuffle_masked(self):
  425. # gh-3263
  426. a = np.ma.masked_values(np.reshape(range(20), (5, 4)) % 3 - 1, -1)
  427. b = np.ma.masked_values(np.arange(20) % 3 - 1, -1)
  428. a_orig = a.copy()
  429. b_orig = b.copy()
  430. for i in range(50):
  431. np.random.shuffle(a)
  432. assert_equal(
  433. sorted(a.data[~a.mask]), sorted(a_orig.data[~a_orig.mask]))
  434. np.random.shuffle(b)
  435. assert_equal(
  436. sorted(b.data[~b.mask]), sorted(b_orig.data[~b_orig.mask]))
  437. @pytest.mark.parametrize("random",
  438. [np.random, np.random.RandomState(), np.random.default_rng()])
  439. def test_shuffle_untyped_warning(self, random):
  440. # Create a dict works like a sequence but isn't one
  441. values = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}
  442. with pytest.warns(UserWarning,
  443. match="you are shuffling a 'dict' object") as rec:
  444. random.shuffle(values)
  445. assert "test_random" in rec[0].filename
  446. @pytest.mark.parametrize("random",
  447. [np.random, np.random.RandomState(), np.random.default_rng()])
  448. @pytest.mark.parametrize("use_array_like", [True, False])
  449. def test_shuffle_no_object_unpacking(self, random, use_array_like):
  450. class MyArr(np.ndarray):
  451. pass
  452. items = [
  453. None, np.array([3]), np.float64(3), np.array(10), np.float64(7)
  454. ]
  455. arr = np.array(items, dtype=object)
  456. item_ids = {id(i) for i in items}
  457. if use_array_like:
  458. arr = arr.view(MyArr)
  459. # The array was created fine, and did not modify any objects:
  460. assert all(id(i) in item_ids for i in arr)
  461. if use_array_like and not isinstance(random, np.random.Generator):
  462. # The old API gives incorrect results, but warns about it.
  463. with pytest.warns(UserWarning,
  464. match="Shuffling a one dimensional array.*"):
  465. random.shuffle(arr)
  466. else:
  467. random.shuffle(arr)
  468. assert all(id(i) in item_ids for i in arr)
  469. def test_shuffle_memoryview(self):
  470. # gh-18273
  471. # allow graceful handling of memoryviews
  472. # (treat the same as arrays)
  473. np.random.seed(self.seed)
  474. a = np.arange(5).data
  475. np.random.shuffle(a)
  476. assert_equal(np.asarray(a), [0, 1, 4, 3, 2])
  477. rng = np.random.RandomState(self.seed)
  478. rng.shuffle(a)
  479. assert_equal(np.asarray(a), [0, 1, 2, 3, 4])
  480. rng = np.random.default_rng(self.seed)
  481. rng.shuffle(a)
  482. assert_equal(np.asarray(a), [4, 1, 0, 3, 2])
  483. def test_shuffle_not_writeable(self):
  484. a = np.zeros(3)
  485. a.flags.writeable = False
  486. with pytest.raises(ValueError, match='read-only'):
  487. np.random.shuffle(a)
  488. def test_beta(self):
  489. np.random.seed(self.seed)
  490. actual = np.random.beta(.1, .9, size=(3, 2))
  491. desired = np.array(
  492. [[1.45341850513746058e-02, 5.31297615662868145e-04],
  493. [1.85366619058432324e-06, 4.19214516800110563e-03],
  494. [1.58405155108498093e-04, 1.26252891949397652e-04]])
  495. assert_array_almost_equal(actual, desired, decimal=15)
  496. def test_binomial(self):
  497. np.random.seed(self.seed)
  498. actual = np.random.binomial(100, .456, size=(3, 2))
  499. desired = np.array([[37, 43],
  500. [42, 48],
  501. [46, 45]])
  502. assert_array_equal(actual, desired)
  503. def test_chisquare(self):
  504. np.random.seed(self.seed)
  505. actual = np.random.chisquare(50, size=(3, 2))
  506. desired = np.array([[63.87858175501090585, 68.68407748911370447],
  507. [65.77116116901505904, 47.09686762438974483],
  508. [72.3828403199695174, 74.18408615260374006]])
  509. assert_array_almost_equal(actual, desired, decimal=13)
  510. def test_dirichlet(self):
  511. np.random.seed(self.seed)
  512. alpha = np.array([51.72840233779265162, 39.74494232180943953])
  513. actual = np.random.mtrand.dirichlet(alpha, size=(3, 2))
  514. desired = np.array([[[0.54539444573611562, 0.45460555426388438],
  515. [0.62345816822039413, 0.37654183177960598]],
  516. [[0.55206000085785778, 0.44793999914214233],
  517. [0.58964023305154301, 0.41035976694845688]],
  518. [[0.59266909280647828, 0.40733090719352177],
  519. [0.56974431743975207, 0.43025568256024799]]])
  520. assert_array_almost_equal(actual, desired, decimal=15)
  521. def test_dirichlet_size(self):
  522. # gh-3173
  523. p = np.array([51.72840233779265162, 39.74494232180943953])
  524. assert_equal(np.random.dirichlet(p, np.uint32(1)).shape, (1, 2))
  525. assert_equal(np.random.dirichlet(p, np.uint32(1)).shape, (1, 2))
  526. assert_equal(np.random.dirichlet(p, np.uint32(1)).shape, (1, 2))
  527. assert_equal(np.random.dirichlet(p, [2, 2]).shape, (2, 2, 2))
  528. assert_equal(np.random.dirichlet(p, (2, 2)).shape, (2, 2, 2))
  529. assert_equal(np.random.dirichlet(p, np.array((2, 2))).shape, (2, 2, 2))
  530. assert_raises(TypeError, np.random.dirichlet, p, float(1))
  531. def test_dirichlet_bad_alpha(self):
  532. # gh-2089
  533. alpha = np.array([5.4e-01, -1.0e-16])
  534. assert_raises(ValueError, np.random.mtrand.dirichlet, alpha)
  535. # gh-15876
  536. assert_raises(ValueError, random.dirichlet, [[5, 1]])
  537. assert_raises(ValueError, random.dirichlet, [[5], [1]])
  538. assert_raises(ValueError, random.dirichlet, [[[5], [1]], [[1], [5]]])
  539. assert_raises(ValueError, random.dirichlet, np.array([[5, 1], [1, 5]]))
  540. def test_exponential(self):
  541. np.random.seed(self.seed)
  542. actual = np.random.exponential(1.1234, size=(3, 2))
  543. desired = np.array([[1.08342649775011624, 1.00607889924557314],
  544. [2.46628830085216721, 2.49668106809923884],
  545. [0.68717433461363442, 1.69175666993575979]])
  546. assert_array_almost_equal(actual, desired, decimal=15)
  547. def test_exponential_0(self):
  548. assert_equal(np.random.exponential(scale=0), 0)
  549. assert_raises(ValueError, np.random.exponential, scale=-0.)
  550. def test_f(self):
  551. np.random.seed(self.seed)
  552. actual = np.random.f(12, 77, size=(3, 2))
  553. desired = np.array([[1.21975394418575878, 1.75135759791559775],
  554. [1.44803115017146489, 1.22108959480396262],
  555. [1.02176975757740629, 1.34431827623300415]])
  556. assert_array_almost_equal(actual, desired, decimal=15)
  557. def test_gamma(self):
  558. np.random.seed(self.seed)
  559. actual = np.random.gamma(5, 3, size=(3, 2))
  560. desired = np.array([[24.60509188649287182, 28.54993563207210627],
  561. [26.13476110204064184, 12.56988482927716078],
  562. [31.71863275789960568, 33.30143302795922011]])
  563. assert_array_almost_equal(actual, desired, decimal=14)
  564. def test_gamma_0(self):
  565. assert_equal(np.random.gamma(shape=0, scale=0), 0)
  566. assert_raises(ValueError, np.random.gamma, shape=-0., scale=-0.)
  567. def test_geometric(self):
  568. np.random.seed(self.seed)
  569. actual = np.random.geometric(.123456789, size=(3, 2))
  570. desired = np.array([[8, 7],
  571. [17, 17],
  572. [5, 12]])
  573. assert_array_equal(actual, desired)
  574. def test_gumbel(self):
  575. np.random.seed(self.seed)
  576. actual = np.random.gumbel(loc=.123456789, scale=2.0, size=(3, 2))
  577. desired = np.array([[0.19591898743416816, 0.34405539668096674],
  578. [-1.4492522252274278, -1.47374816298446865],
  579. [1.10651090478803416, -0.69535848626236174]])
  580. assert_array_almost_equal(actual, desired, decimal=15)
  581. def test_gumbel_0(self):
  582. assert_equal(np.random.gumbel(scale=0), 0)
  583. assert_raises(ValueError, np.random.gumbel, scale=-0.)
  584. def test_hypergeometric(self):
  585. np.random.seed(self.seed)
  586. actual = np.random.hypergeometric(10, 5, 14, size=(3, 2))
  587. desired = np.array([[10, 10],
  588. [10, 10],
  589. [9, 9]])
  590. assert_array_equal(actual, desired)
  591. # Test nbad = 0
  592. actual = np.random.hypergeometric(5, 0, 3, size=4)
  593. desired = np.array([3, 3, 3, 3])
  594. assert_array_equal(actual, desired)
  595. actual = np.random.hypergeometric(15, 0, 12, size=4)
  596. desired = np.array([12, 12, 12, 12])
  597. assert_array_equal(actual, desired)
  598. # Test ngood = 0
  599. actual = np.random.hypergeometric(0, 5, 3, size=4)
  600. desired = np.array([0, 0, 0, 0])
  601. assert_array_equal(actual, desired)
  602. actual = np.random.hypergeometric(0, 15, 12, size=4)
  603. desired = np.array([0, 0, 0, 0])
  604. assert_array_equal(actual, desired)
  605. def test_laplace(self):
  606. np.random.seed(self.seed)
  607. actual = np.random.laplace(loc=.123456789, scale=2.0, size=(3, 2))
  608. desired = np.array([[0.66599721112760157, 0.52829452552221945],
  609. [3.12791959514407125, 3.18202813572992005],
  610. [-0.05391065675859356, 1.74901336242837324]])
  611. assert_array_almost_equal(actual, desired, decimal=15)
  612. def test_laplace_0(self):
  613. assert_equal(np.random.laplace(scale=0), 0)
  614. assert_raises(ValueError, np.random.laplace, scale=-0.)
  615. def test_logistic(self):
  616. np.random.seed(self.seed)
  617. actual = np.random.logistic(loc=.123456789, scale=2.0, size=(3, 2))
  618. desired = np.array([[1.09232835305011444, 0.8648196662399954],
  619. [4.27818590694950185, 4.33897006346929714],
  620. [-0.21682183359214885, 2.63373365386060332]])
  621. assert_array_almost_equal(actual, desired, decimal=15)
  622. def test_lognormal(self):
  623. np.random.seed(self.seed)
  624. actual = np.random.lognormal(mean=.123456789, sigma=2.0, size=(3, 2))
  625. desired = np.array([[16.50698631688883822, 36.54846706092654784],
  626. [22.67886599981281748, 0.71617561058995771],
  627. [65.72798501792723869, 86.84341601437161273]])
  628. assert_array_almost_equal(actual, desired, decimal=13)
  629. def test_lognormal_0(self):
  630. assert_equal(np.random.lognormal(sigma=0), 1)
  631. assert_raises(ValueError, np.random.lognormal, sigma=-0.)
  632. def test_logseries(self):
  633. np.random.seed(self.seed)
  634. actual = np.random.logseries(p=.923456789, size=(3, 2))
  635. desired = np.array([[2, 2],
  636. [6, 17],
  637. [3, 6]])
  638. assert_array_equal(actual, desired)
  639. def test_multinomial(self):
  640. np.random.seed(self.seed)
  641. actual = np.random.multinomial(20, [1/6.]*6, size=(3, 2))
  642. desired = np.array([[[4, 3, 5, 4, 2, 2],
  643. [5, 2, 8, 2, 2, 1]],
  644. [[3, 4, 3, 6, 0, 4],
  645. [2, 1, 4, 3, 6, 4]],
  646. [[4, 4, 2, 5, 2, 3],
  647. [4, 3, 4, 2, 3, 4]]])
  648. assert_array_equal(actual, desired)
  649. def test_multivariate_normal(self):
  650. np.random.seed(self.seed)
  651. mean = (.123456789, 10)
  652. cov = [[1, 0], [0, 1]]
  653. size = (3, 2)
  654. actual = np.random.multivariate_normal(mean, cov, size)
  655. desired = np.array([[[1.463620246718631, 11.73759122771936],
  656. [1.622445133300628, 9.771356667546383]],
  657. [[2.154490787682787, 12.170324946056553],
  658. [1.719909438201865, 9.230548443648306]],
  659. [[0.689515026297799, 9.880729819607714],
  660. [-0.023054015651998, 9.201096623542879]]])
  661. assert_array_almost_equal(actual, desired, decimal=15)
  662. # Check for default size, was raising deprecation warning
  663. actual = np.random.multivariate_normal(mean, cov)
  664. desired = np.array([0.895289569463708, 9.17180864067987])
  665. assert_array_almost_equal(actual, desired, decimal=15)
  666. # Check that non positive-semidefinite covariance warns with
  667. # RuntimeWarning
  668. mean = [0, 0]
  669. cov = [[1, 2], [2, 1]]
  670. assert_warns(RuntimeWarning, np.random.multivariate_normal, mean, cov)
  671. # and that it doesn't warn with RuntimeWarning check_valid='ignore'
  672. assert_no_warnings(np.random.multivariate_normal, mean, cov,
  673. check_valid='ignore')
  674. # and that it raises with RuntimeWarning check_valid='raises'
  675. assert_raises(ValueError, np.random.multivariate_normal, mean, cov,
  676. check_valid='raise')
  677. cov = np.array([[1, 0.1], [0.1, 1]], dtype=np.float32)
  678. with suppress_warnings() as sup:
  679. np.random.multivariate_normal(mean, cov)
  680. w = sup.record(RuntimeWarning)
  681. assert len(w) == 0
  682. def test_negative_binomial(self):
  683. np.random.seed(self.seed)
  684. actual = np.random.negative_binomial(n=100, p=.12345, size=(3, 2))
  685. desired = np.array([[848, 841],
  686. [892, 611],
  687. [779, 647]])
  688. assert_array_equal(actual, desired)
  689. def test_noncentral_chisquare(self):
  690. np.random.seed(self.seed)
  691. actual = np.random.noncentral_chisquare(df=5, nonc=5, size=(3, 2))
  692. desired = np.array([[23.91905354498517511, 13.35324692733826346],
  693. [31.22452661329736401, 16.60047399466177254],
  694. [5.03461598262724586, 17.94973089023519464]])
  695. assert_array_almost_equal(actual, desired, decimal=14)
  696. actual = np.random.noncentral_chisquare(df=.5, nonc=.2, size=(3, 2))
  697. desired = np.array([[1.47145377828516666, 0.15052899268012659],
  698. [0.00943803056963588, 1.02647251615666169],
  699. [0.332334982684171, 0.15451287602753125]])
  700. assert_array_almost_equal(actual, desired, decimal=14)
  701. np.random.seed(self.seed)
  702. actual = np.random.noncentral_chisquare(df=5, nonc=0, size=(3, 2))
  703. desired = np.array([[9.597154162763948, 11.725484450296079],
  704. [10.413711048138335, 3.694475922923986],
  705. [13.484222138963087, 14.377255424602957]])
  706. assert_array_almost_equal(actual, desired, decimal=14)
  707. def test_noncentral_f(self):
  708. np.random.seed(self.seed)
  709. actual = np.random.noncentral_f(dfnum=5, dfden=2, nonc=1,
  710. size=(3, 2))
  711. desired = np.array([[1.40598099674926669, 0.34207973179285761],
  712. [3.57715069265772545, 7.92632662577829805],
  713. [0.43741599463544162, 1.1774208752428319]])
  714. assert_array_almost_equal(actual, desired, decimal=14)
  715. def test_normal(self):
  716. np.random.seed(self.seed)
  717. actual = np.random.normal(loc=.123456789, scale=2.0, size=(3, 2))
  718. desired = np.array([[2.80378370443726244, 3.59863924443872163],
  719. [3.121433477601256, -0.33382987590723379],
  720. [4.18552478636557357, 4.46410668111310471]])
  721. assert_array_almost_equal(actual, desired, decimal=15)
  722. def test_normal_0(self):
  723. assert_equal(np.random.normal(scale=0), 0)
  724. assert_raises(ValueError, np.random.normal, scale=-0.)
  725. def test_pareto(self):
  726. np.random.seed(self.seed)
  727. actual = np.random.pareto(a=.123456789, size=(3, 2))
  728. desired = np.array(
  729. [[2.46852460439034849e+03, 1.41286880810518346e+03],
  730. [5.28287797029485181e+07, 6.57720981047328785e+07],
  731. [1.40840323350391515e+02, 1.98390255135251704e+05]])
  732. # For some reason on 32-bit x86 Ubuntu 12.10 the [1, 0] entry in this
  733. # matrix differs by 24 nulps. Discussion:
  734. # https://mail.python.org/pipermail/numpy-discussion/2012-September/063801.html
  735. # Consensus is that this is probably some gcc quirk that affects
  736. # rounding but not in any important way, so we just use a looser
  737. # tolerance on this test:
  738. np.testing.assert_array_almost_equal_nulp(actual, desired, nulp=30)
  739. def test_poisson(self):
  740. np.random.seed(self.seed)
  741. actual = np.random.poisson(lam=.123456789, size=(3, 2))
  742. desired = np.array([[0, 0],
  743. [1, 0],
  744. [0, 0]])
  745. assert_array_equal(actual, desired)
  746. def test_poisson_exceptions(self):
  747. lambig = np.iinfo('l').max
  748. lamneg = -1
  749. assert_raises(ValueError, np.random.poisson, lamneg)
  750. assert_raises(ValueError, np.random.poisson, [lamneg]*10)
  751. assert_raises(ValueError, np.random.poisson, lambig)
  752. assert_raises(ValueError, np.random.poisson, [lambig]*10)
  753. def test_power(self):
  754. np.random.seed(self.seed)
  755. actual = np.random.power(a=.123456789, size=(3, 2))
  756. desired = np.array([[0.02048932883240791, 0.01424192241128213],
  757. [0.38446073748535298, 0.39499689943484395],
  758. [0.00177699707563439, 0.13115505880863756]])
  759. assert_array_almost_equal(actual, desired, decimal=15)
  760. def test_rayleigh(self):
  761. np.random.seed(self.seed)
  762. actual = np.random.rayleigh(scale=10, size=(3, 2))
  763. desired = np.array([[13.8882496494248393, 13.383318339044731],
  764. [20.95413364294492098, 21.08285015800712614],
  765. [11.06066537006854311, 17.35468505778271009]])
  766. assert_array_almost_equal(actual, desired, decimal=14)
  767. def test_rayleigh_0(self):
  768. assert_equal(np.random.rayleigh(scale=0), 0)
  769. assert_raises(ValueError, np.random.rayleigh, scale=-0.)
  770. def test_standard_cauchy(self):
  771. np.random.seed(self.seed)
  772. actual = np.random.standard_cauchy(size=(3, 2))
  773. desired = np.array([[0.77127660196445336, -6.55601161955910605],
  774. [0.93582023391158309, -2.07479293013759447],
  775. [-4.74601644297011926, 0.18338989290760804]])
  776. assert_array_almost_equal(actual, desired, decimal=15)
  777. def test_standard_exponential(self):
  778. np.random.seed(self.seed)
  779. actual = np.random.standard_exponential(size=(3, 2))
  780. desired = np.array([[0.96441739162374596, 0.89556604882105506],
  781. [2.1953785836319808, 2.22243285392490542],
  782. [0.6116915921431676, 1.50592546727413201]])
  783. assert_array_almost_equal(actual, desired, decimal=15)
  784. def test_standard_gamma(self):
  785. np.random.seed(self.seed)
  786. actual = np.random.standard_gamma(shape=3, size=(3, 2))
  787. desired = np.array([[5.50841531318455058, 6.62953470301903103],
  788. [5.93988484943779227, 2.31044849402133989],
  789. [7.54838614231317084, 8.012756093271868]])
  790. assert_array_almost_equal(actual, desired, decimal=14)
  791. def test_standard_gamma_0(self):
  792. assert_equal(np.random.standard_gamma(shape=0), 0)
  793. assert_raises(ValueError, np.random.standard_gamma, shape=-0.)
  794. def test_standard_normal(self):
  795. np.random.seed(self.seed)
  796. actual = np.random.standard_normal(size=(3, 2))
  797. desired = np.array([[1.34016345771863121, 1.73759122771936081],
  798. [1.498988344300628, -0.2286433324536169],
  799. [2.031033998682787, 2.17032494605655257]])
  800. assert_array_almost_equal(actual, desired, decimal=15)
  801. def test_standard_t(self):
  802. np.random.seed(self.seed)
  803. actual = np.random.standard_t(df=10, size=(3, 2))
  804. desired = np.array([[0.97140611862659965, -0.08830486548450577],
  805. [1.36311143689505321, -0.55317463909867071],
  806. [-0.18473749069684214, 0.61181537341755321]])
  807. assert_array_almost_equal(actual, desired, decimal=15)
  808. def test_triangular(self):
  809. np.random.seed(self.seed)
  810. actual = np.random.triangular(left=5.12, mode=10.23, right=20.34,
  811. size=(3, 2))
  812. desired = np.array([[12.68117178949215784, 12.4129206149193152],
  813. [16.20131377335158263, 16.25692138747600524],
  814. [11.20400690911820263, 14.4978144835829923]])
  815. assert_array_almost_equal(actual, desired, decimal=14)
  816. def test_uniform(self):
  817. np.random.seed(self.seed)
  818. actual = np.random.uniform(low=1.23, high=10.54, size=(3, 2))
  819. desired = np.array([[6.99097932346268003, 6.73801597444323974],
  820. [9.50364421400426274, 9.53130618907631089],
  821. [5.48995325769805476, 8.47493103280052118]])
  822. assert_array_almost_equal(actual, desired, decimal=15)
  823. def test_uniform_range_bounds(self):
  824. fmin = np.finfo('float').min
  825. fmax = np.finfo('float').max
  826. func = np.random.uniform
  827. assert_raises(OverflowError, func, -np.inf, 0)
  828. assert_raises(OverflowError, func, 0, np.inf)
  829. assert_raises(OverflowError, func, fmin, fmax)
  830. assert_raises(OverflowError, func, [-np.inf], [0])
  831. assert_raises(OverflowError, func, [0], [np.inf])
  832. # (fmax / 1e17) - fmin is within range, so this should not throw
  833. # account for i386 extended precision DBL_MAX / 1e17 + DBL_MAX >
  834. # DBL_MAX by increasing fmin a bit
  835. np.random.uniform(low=np.nextafter(fmin, 1), high=fmax / 1e17)
  836. def test_scalar_exception_propagation(self):
  837. # Tests that exceptions are correctly propagated in distributions
  838. # when called with objects that throw exceptions when converted to
  839. # scalars.
  840. #
  841. # Regression test for gh: 8865
  842. class ThrowingFloat(np.ndarray):
  843. def __float__(self):
  844. raise TypeError
  845. throwing_float = np.array(1.0).view(ThrowingFloat)
  846. assert_raises(TypeError, np.random.uniform, throwing_float,
  847. throwing_float)
  848. class ThrowingInteger(np.ndarray):
  849. def __int__(self):
  850. raise TypeError
  851. __index__ = __int__
  852. throwing_int = np.array(1).view(ThrowingInteger)
  853. assert_raises(TypeError, np.random.hypergeometric, throwing_int, 1, 1)
  854. def test_vonmises(self):
  855. np.random.seed(self.seed)
  856. actual = np.random.vonmises(mu=1.23, kappa=1.54, size=(3, 2))
  857. desired = np.array([[2.28567572673902042, 2.89163838442285037],
  858. [0.38198375564286025, 2.57638023113890746],
  859. [1.19153771588353052, 1.83509849681825354]])
  860. assert_array_almost_equal(actual, desired, decimal=15)
  861. def test_vonmises_small(self):
  862. # check infinite loop, gh-4720
  863. np.random.seed(self.seed)
  864. r = np.random.vonmises(mu=0., kappa=1.1e-8, size=10**6)
  865. np.testing.assert_(np.isfinite(r).all())
  866. def test_wald(self):
  867. np.random.seed(self.seed)
  868. actual = np.random.wald(mean=1.23, scale=1.54, size=(3, 2))
  869. desired = np.array([[3.82935265715889983, 5.13125249184285526],
  870. [0.35045403618358717, 1.50832396872003538],
  871. [0.24124319895843183, 0.22031101461955038]])
  872. assert_array_almost_equal(actual, desired, decimal=14)
  873. def test_weibull(self):
  874. np.random.seed(self.seed)
  875. actual = np.random.weibull(a=1.23, size=(3, 2))
  876. desired = np.array([[0.97097342648766727, 0.91422896443565516],
  877. [1.89517770034962929, 1.91414357960479564],
  878. [0.67057783752390987, 1.39494046635066793]])
  879. assert_array_almost_equal(actual, desired, decimal=15)
  880. def test_weibull_0(self):
  881. np.random.seed(self.seed)
  882. assert_equal(np.random.weibull(a=0, size=12), np.zeros(12))
  883. assert_raises(ValueError, np.random.weibull, a=-0.)
  884. def test_zipf(self):
  885. np.random.seed(self.seed)
  886. actual = np.random.zipf(a=1.23, size=(3, 2))
  887. desired = np.array([[66, 29],
  888. [1, 1],
  889. [3, 13]])
  890. assert_array_equal(actual, desired)
  891. class TestBroadcast:
  892. # tests that functions that broadcast behave
  893. # correctly when presented with non-scalar arguments
  894. def setup_method(self):
  895. self.seed = 123456789
  896. def setSeed(self):
  897. np.random.seed(self.seed)
  898. # TODO: Include test for randint once it can broadcast
  899. # Can steal the test written in PR #6938
  900. def test_uniform(self):
  901. low = [0]
  902. high = [1]
  903. uniform = np.random.uniform
  904. desired = np.array([0.53283302478975902,
  905. 0.53413660089041659,
  906. 0.50955303552646702])
  907. self.setSeed()
  908. actual = uniform(low * 3, high)
  909. assert_array_almost_equal(actual, desired, decimal=14)
  910. self.setSeed()
  911. actual = uniform(low, high * 3)
  912. assert_array_almost_equal(actual, desired, decimal=14)
  913. def test_normal(self):
  914. loc = [0]
  915. scale = [1]
  916. bad_scale = [-1]
  917. normal = np.random.normal
  918. desired = np.array([2.2129019979039612,
  919. 2.1283977976520019,
  920. 1.8417114045748335])
  921. self.setSeed()
  922. actual = normal(loc * 3, scale)
  923. assert_array_almost_equal(actual, desired, decimal=14)
  924. assert_raises(ValueError, normal, loc * 3, bad_scale)
  925. self.setSeed()
  926. actual = normal(loc, scale * 3)
  927. assert_array_almost_equal(actual, desired, decimal=14)
  928. assert_raises(ValueError, normal, loc, bad_scale * 3)
  929. def test_beta(self):
  930. a = [1]
  931. b = [2]
  932. bad_a = [-1]
  933. bad_b = [-2]
  934. beta = np.random.beta
  935. desired = np.array([0.19843558305989056,
  936. 0.075230336409423643,
  937. 0.24976865978980844])
  938. self.setSeed()
  939. actual = beta(a * 3, b)
  940. assert_array_almost_equal(actual, desired, decimal=14)
  941. assert_raises(ValueError, beta, bad_a * 3, b)
  942. assert_raises(ValueError, beta, a * 3, bad_b)
  943. self.setSeed()
  944. actual = beta(a, b * 3)
  945. assert_array_almost_equal(actual, desired, decimal=14)
  946. assert_raises(ValueError, beta, bad_a, b * 3)
  947. assert_raises(ValueError, beta, a, bad_b * 3)
  948. def test_exponential(self):
  949. scale = [1]
  950. bad_scale = [-1]
  951. exponential = np.random.exponential
  952. desired = np.array([0.76106853658845242,
  953. 0.76386282278691653,
  954. 0.71243813125891797])
  955. self.setSeed()
  956. actual = exponential(scale * 3)
  957. assert_array_almost_equal(actual, desired, decimal=14)
  958. assert_raises(ValueError, exponential, bad_scale * 3)
  959. def test_standard_gamma(self):
  960. shape = [1]
  961. bad_shape = [-1]
  962. std_gamma = np.random.standard_gamma
  963. desired = np.array([0.76106853658845242,
  964. 0.76386282278691653,
  965. 0.71243813125891797])
  966. self.setSeed()
  967. actual = std_gamma(shape * 3)
  968. assert_array_almost_equal(actual, desired, decimal=14)
  969. assert_raises(ValueError, std_gamma, bad_shape * 3)
  970. def test_gamma(self):
  971. shape = [1]
  972. scale = [2]
  973. bad_shape = [-1]
  974. bad_scale = [-2]
  975. gamma = np.random.gamma
  976. desired = np.array([1.5221370731769048,
  977. 1.5277256455738331,
  978. 1.4248762625178359])
  979. self.setSeed()
  980. actual = gamma(shape * 3, scale)
  981. assert_array_almost_equal(actual, desired, decimal=14)
  982. assert_raises(ValueError, gamma, bad_shape * 3, scale)
  983. assert_raises(ValueError, gamma, shape * 3, bad_scale)
  984. self.setSeed()
  985. actual = gamma(shape, scale * 3)
  986. assert_array_almost_equal(actual, desired, decimal=14)
  987. assert_raises(ValueError, gamma, bad_shape, scale * 3)
  988. assert_raises(ValueError, gamma, shape, bad_scale * 3)
  989. def test_f(self):
  990. dfnum = [1]
  991. dfden = [2]
  992. bad_dfnum = [-1]
  993. bad_dfden = [-2]
  994. f = np.random.f
  995. desired = np.array([0.80038951638264799,
  996. 0.86768719635363512,
  997. 2.7251095168386801])
  998. self.setSeed()
  999. actual = f(dfnum * 3, dfden)
  1000. assert_array_almost_equal(actual, desired, decimal=14)
  1001. assert_raises(ValueError, f, bad_dfnum * 3, dfden)
  1002. assert_raises(ValueError, f, dfnum * 3, bad_dfden)
  1003. self.setSeed()
  1004. actual = f(dfnum, dfden * 3)
  1005. assert_array_almost_equal(actual, desired, decimal=14)
  1006. assert_raises(ValueError, f, bad_dfnum, dfden * 3)
  1007. assert_raises(ValueError, f, dfnum, bad_dfden * 3)
  1008. def test_noncentral_f(self):
  1009. dfnum = [2]
  1010. dfden = [3]
  1011. nonc = [4]
  1012. bad_dfnum = [0]
  1013. bad_dfden = [-1]
  1014. bad_nonc = [-2]
  1015. nonc_f = np.random.noncentral_f
  1016. desired = np.array([9.1393943263705211,
  1017. 13.025456344595602,
  1018. 8.8018098359100545])
  1019. self.setSeed()
  1020. actual = nonc_f(dfnum * 3, dfden, nonc)
  1021. assert_array_almost_equal(actual, desired, decimal=14)
  1022. assert_raises(ValueError, nonc_f, bad_dfnum * 3, dfden, nonc)
  1023. assert_raises(ValueError, nonc_f, dfnum * 3, bad_dfden, nonc)
  1024. assert_raises(ValueError, nonc_f, dfnum * 3, dfden, bad_nonc)
  1025. self.setSeed()
  1026. actual = nonc_f(dfnum, dfden * 3, nonc)
  1027. assert_array_almost_equal(actual, desired, decimal=14)
  1028. assert_raises(ValueError, nonc_f, bad_dfnum, dfden * 3, nonc)
  1029. assert_raises(ValueError, nonc_f, dfnum, bad_dfden * 3, nonc)
  1030. assert_raises(ValueError, nonc_f, dfnum, dfden * 3, bad_nonc)
  1031. self.setSeed()
  1032. actual = nonc_f(dfnum, dfden, nonc * 3)
  1033. assert_array_almost_equal(actual, desired, decimal=14)
  1034. assert_raises(ValueError, nonc_f, bad_dfnum, dfden, nonc * 3)
  1035. assert_raises(ValueError, nonc_f, dfnum, bad_dfden, nonc * 3)
  1036. assert_raises(ValueError, nonc_f, dfnum, dfden, bad_nonc * 3)
  1037. def test_noncentral_f_small_df(self):
  1038. self.setSeed()
  1039. desired = np.array([6.869638627492048, 0.785880199263955])
  1040. actual = np.random.noncentral_f(0.9, 0.9, 2, size=2)
  1041. assert_array_almost_equal(actual, desired, decimal=14)
  1042. def test_chisquare(self):
  1043. df = [1]
  1044. bad_df = [-1]
  1045. chisquare = np.random.chisquare
  1046. desired = np.array([0.57022801133088286,
  1047. 0.51947702108840776,
  1048. 0.1320969254923558])
  1049. self.setSeed()
  1050. actual = chisquare(df * 3)
  1051. assert_array_almost_equal(actual, desired, decimal=14)
  1052. assert_raises(ValueError, chisquare, bad_df * 3)
  1053. def test_noncentral_chisquare(self):
  1054. df = [1]
  1055. nonc = [2]
  1056. bad_df = [-1]
  1057. bad_nonc = [-2]
  1058. nonc_chi = np.random.noncentral_chisquare
  1059. desired = np.array([9.0015599467913763,
  1060. 4.5804135049718742,
  1061. 6.0872302432834564])
  1062. self.setSeed()
  1063. actual = nonc_chi(df * 3, nonc)
  1064. assert_array_almost_equal(actual, desired, decimal=14)
  1065. assert_raises(ValueError, nonc_chi, bad_df * 3, nonc)
  1066. assert_raises(ValueError, nonc_chi, df * 3, bad_nonc)
  1067. self.setSeed()
  1068. actual = nonc_chi(df, nonc * 3)
  1069. assert_array_almost_equal(actual, desired, decimal=14)
  1070. assert_raises(ValueError, nonc_chi, bad_df, nonc * 3)
  1071. assert_raises(ValueError, nonc_chi, df, bad_nonc * 3)
  1072. def test_standard_t(self):
  1073. df = [1]
  1074. bad_df = [-1]
  1075. t = np.random.standard_t
  1076. desired = np.array([3.0702872575217643,
  1077. 5.8560725167361607,
  1078. 1.0274791436474273])
  1079. self.setSeed()
  1080. actual = t(df * 3)
  1081. assert_array_almost_equal(actual, desired, decimal=14)
  1082. assert_raises(ValueError, t, bad_df * 3)
  1083. def test_vonmises(self):
  1084. mu = [2]
  1085. kappa = [1]
  1086. bad_kappa = [-1]
  1087. vonmises = np.random.vonmises
  1088. desired = np.array([2.9883443664201312,
  1089. -2.7064099483995943,
  1090. -1.8672476700665914])
  1091. self.setSeed()
  1092. actual = vonmises(mu * 3, kappa)
  1093. assert_array_almost_equal(actual, desired, decimal=14)
  1094. assert_raises(ValueError, vonmises, mu * 3, bad_kappa)
  1095. self.setSeed()
  1096. actual = vonmises(mu, kappa * 3)
  1097. assert_array_almost_equal(actual, desired, decimal=14)
  1098. assert_raises(ValueError, vonmises, mu, bad_kappa * 3)
  1099. def test_pareto(self):
  1100. a = [1]
  1101. bad_a = [-1]
  1102. pareto = np.random.pareto
  1103. desired = np.array([1.1405622680198362,
  1104. 1.1465519762044529,
  1105. 1.0389564467453547])
  1106. self.setSeed()
  1107. actual = pareto(a * 3)
  1108. assert_array_almost_equal(actual, desired, decimal=14)
  1109. assert_raises(ValueError, pareto, bad_a * 3)
  1110. def test_weibull(self):
  1111. a = [1]
  1112. bad_a = [-1]
  1113. weibull = np.random.weibull
  1114. desired = np.array([0.76106853658845242,
  1115. 0.76386282278691653,
  1116. 0.71243813125891797])
  1117. self.setSeed()
  1118. actual = weibull(a * 3)
  1119. assert_array_almost_equal(actual, desired, decimal=14)
  1120. assert_raises(ValueError, weibull, bad_a * 3)
  1121. def test_power(self):
  1122. a = [1]
  1123. bad_a = [-1]
  1124. power = np.random.power
  1125. desired = np.array([0.53283302478975902,
  1126. 0.53413660089041659,
  1127. 0.50955303552646702])
  1128. self.setSeed()
  1129. actual = power(a * 3)
  1130. assert_array_almost_equal(actual, desired, decimal=14)
  1131. assert_raises(ValueError, power, bad_a * 3)
  1132. def test_laplace(self):
  1133. loc = [0]
  1134. scale = [1]
  1135. bad_scale = [-1]
  1136. laplace = np.random.laplace
  1137. desired = np.array([0.067921356028507157,
  1138. 0.070715642226971326,
  1139. 0.019290950698972624])
  1140. self.setSeed()
  1141. actual = laplace(loc * 3, scale)
  1142. assert_array_almost_equal(actual, desired, decimal=14)
  1143. assert_raises(ValueError, laplace, loc * 3, bad_scale)
  1144. self.setSeed()
  1145. actual = laplace(loc, scale * 3)
  1146. assert_array_almost_equal(actual, desired, decimal=14)
  1147. assert_raises(ValueError, laplace, loc, bad_scale * 3)
  1148. def test_gumbel(self):
  1149. loc = [0]
  1150. scale = [1]
  1151. bad_scale = [-1]
  1152. gumbel = np.random.gumbel
  1153. desired = np.array([0.2730318639556768,
  1154. 0.26936705726291116,
  1155. 0.33906220393037939])
  1156. self.setSeed()
  1157. actual = gumbel(loc * 3, scale)
  1158. assert_array_almost_equal(actual, desired, decimal=14)
  1159. assert_raises(ValueError, gumbel, loc * 3, bad_scale)
  1160. self.setSeed()
  1161. actual = gumbel(loc, scale * 3)
  1162. assert_array_almost_equal(actual, desired, decimal=14)
  1163. assert_raises(ValueError, gumbel, loc, bad_scale * 3)
  1164. def test_logistic(self):
  1165. loc = [0]
  1166. scale = [1]
  1167. bad_scale = [-1]
  1168. logistic = np.random.logistic
  1169. desired = np.array([0.13152135837586171,
  1170. 0.13675915696285773,
  1171. 0.038216792802833396])
  1172. self.setSeed()
  1173. actual = logistic(loc * 3, scale)
  1174. assert_array_almost_equal(actual, desired, decimal=14)
  1175. assert_raises(ValueError, logistic, loc * 3, bad_scale)
  1176. self.setSeed()
  1177. actual = logistic(loc, scale * 3)
  1178. assert_array_almost_equal(actual, desired, decimal=14)
  1179. assert_raises(ValueError, logistic, loc, bad_scale * 3)
  1180. def test_lognormal(self):
  1181. mean = [0]
  1182. sigma = [1]
  1183. bad_sigma = [-1]
  1184. lognormal = np.random.lognormal
  1185. desired = np.array([9.1422086044848427,
  1186. 8.4013952870126261,
  1187. 6.3073234116578671])
  1188. self.setSeed()
  1189. actual = lognormal(mean * 3, sigma)
  1190. assert_array_almost_equal(actual, desired, decimal=14)
  1191. assert_raises(ValueError, lognormal, mean * 3, bad_sigma)
  1192. self.setSeed()
  1193. actual = lognormal(mean, sigma * 3)
  1194. assert_array_almost_equal(actual, desired, decimal=14)
  1195. assert_raises(ValueError, lognormal, mean, bad_sigma * 3)
  1196. def test_rayleigh(self):
  1197. scale = [1]
  1198. bad_scale = [-1]
  1199. rayleigh = np.random.rayleigh
  1200. desired = np.array([1.2337491937897689,
  1201. 1.2360119924878694,
  1202. 1.1936818095781789])
  1203. self.setSeed()
  1204. actual = rayleigh(scale * 3)
  1205. assert_array_almost_equal(actual, desired, decimal=14)
  1206. assert_raises(ValueError, rayleigh, bad_scale * 3)
  1207. def test_wald(self):
  1208. mean = [0.5]
  1209. scale = [1]
  1210. bad_mean = [0]
  1211. bad_scale = [-2]
  1212. wald = np.random.wald
  1213. desired = np.array([0.11873681120271318,
  1214. 0.12450084820795027,
  1215. 0.9096122728408238])
  1216. self.setSeed()
  1217. actual = wald(mean * 3, scale)
  1218. assert_array_almost_equal(actual, desired, decimal=14)
  1219. assert_raises(ValueError, wald, bad_mean * 3, scale)
  1220. assert_raises(ValueError, wald, mean * 3, bad_scale)
  1221. self.setSeed()
  1222. actual = wald(mean, scale * 3)
  1223. assert_array_almost_equal(actual, desired, decimal=14)
  1224. assert_raises(ValueError, wald, bad_mean, scale * 3)
  1225. assert_raises(ValueError, wald, mean, bad_scale * 3)
  1226. assert_raises(ValueError, wald, 0.0, 1)
  1227. assert_raises(ValueError, wald, 0.5, 0.0)
  1228. def test_triangular(self):
  1229. left = [1]
  1230. right = [3]
  1231. mode = [2]
  1232. bad_left_one = [3]
  1233. bad_mode_one = [4]
  1234. bad_left_two, bad_mode_two = right * 2
  1235. triangular = np.random.triangular
  1236. desired = np.array([2.03339048710429,
  1237. 2.0347400359389356,
  1238. 2.0095991069536208])
  1239. self.setSeed()
  1240. actual = triangular(left * 3, mode, right)
  1241. assert_array_almost_equal(actual, desired, decimal=14)
  1242. assert_raises(ValueError, triangular, bad_left_one * 3, mode, right)
  1243. assert_raises(ValueError, triangular, left * 3, bad_mode_one, right)
  1244. assert_raises(ValueError, triangular, bad_left_two * 3, bad_mode_two,
  1245. right)
  1246. self.setSeed()
  1247. actual = triangular(left, mode * 3, right)
  1248. assert_array_almost_equal(actual, desired, decimal=14)
  1249. assert_raises(ValueError, triangular, bad_left_one, mode * 3, right)
  1250. assert_raises(ValueError, triangular, left, bad_mode_one * 3, right)
  1251. assert_raises(ValueError, triangular, bad_left_two, bad_mode_two * 3,
  1252. right)
  1253. self.setSeed()
  1254. actual = triangular(left, mode, right * 3)
  1255. assert_array_almost_equal(actual, desired, decimal=14)
  1256. assert_raises(ValueError, triangular, bad_left_one, mode, right * 3)
  1257. assert_raises(ValueError, triangular, left, bad_mode_one, right * 3)
  1258. assert_raises(ValueError, triangular, bad_left_two, bad_mode_two,
  1259. right * 3)
  1260. def test_binomial(self):
  1261. n = [1]
  1262. p = [0.5]
  1263. bad_n = [-1]
  1264. bad_p_one = [-1]
  1265. bad_p_two = [1.5]
  1266. binom = np.random.binomial
  1267. desired = np.array([1, 1, 1])
  1268. self.setSeed()
  1269. actual = binom(n * 3, p)
  1270. assert_array_equal(actual, desired)
  1271. assert_raises(ValueError, binom, bad_n * 3, p)
  1272. assert_raises(ValueError, binom, n * 3, bad_p_one)
  1273. assert_raises(ValueError, binom, n * 3, bad_p_two)
  1274. self.setSeed()
  1275. actual = binom(n, p * 3)
  1276. assert_array_equal(actual, desired)
  1277. assert_raises(ValueError, binom, bad_n, p * 3)
  1278. assert_raises(ValueError, binom, n, bad_p_one * 3)
  1279. assert_raises(ValueError, binom, n, bad_p_two * 3)
  1280. def test_negative_binomial(self):
  1281. n = [1]
  1282. p = [0.5]
  1283. bad_n = [-1]
  1284. bad_p_one = [-1]
  1285. bad_p_two = [1.5]
  1286. neg_binom = np.random.negative_binomial
  1287. desired = np.array([1, 0, 1])
  1288. self.setSeed()
  1289. actual = neg_binom(n * 3, p)
  1290. assert_array_equal(actual, desired)
  1291. assert_raises(ValueError, neg_binom, bad_n * 3, p)
  1292. assert_raises(ValueError, neg_binom, n * 3, bad_p_one)
  1293. assert_raises(ValueError, neg_binom, n * 3, bad_p_two)
  1294. self.setSeed()
  1295. actual = neg_binom(n, p * 3)
  1296. assert_array_equal(actual, desired)
  1297. assert_raises(ValueError, neg_binom, bad_n, p * 3)
  1298. assert_raises(ValueError, neg_binom, n, bad_p_one * 3)
  1299. assert_raises(ValueError, neg_binom, n, bad_p_two * 3)
  1300. def test_poisson(self):
  1301. max_lam = np.random.RandomState()._poisson_lam_max
  1302. lam = [1]
  1303. bad_lam_one = [-1]
  1304. bad_lam_two = [max_lam * 2]
  1305. poisson = np.random.poisson
  1306. desired = np.array([1, 1, 0])
  1307. self.setSeed()
  1308. actual = poisson(lam * 3)
  1309. assert_array_equal(actual, desired)
  1310. assert_raises(ValueError, poisson, bad_lam_one * 3)
  1311. assert_raises(ValueError, poisson, bad_lam_two * 3)
  1312. def test_zipf(self):
  1313. a = [2]
  1314. bad_a = [0]
  1315. zipf = np.random.zipf
  1316. desired = np.array([2, 2, 1])
  1317. self.setSeed()
  1318. actual = zipf(a * 3)
  1319. assert_array_equal(actual, desired)
  1320. assert_raises(ValueError, zipf, bad_a * 3)
  1321. with np.errstate(invalid='ignore'):
  1322. assert_raises(ValueError, zipf, np.nan)
  1323. assert_raises(ValueError, zipf, [0, 0, np.nan])
  1324. def test_geometric(self):
  1325. p = [0.5]
  1326. bad_p_one = [-1]
  1327. bad_p_two = [1.5]
  1328. geom = np.random.geometric
  1329. desired = np.array([2, 2, 2])
  1330. self.setSeed()
  1331. actual = geom(p * 3)
  1332. assert_array_equal(actual, desired)
  1333. assert_raises(ValueError, geom, bad_p_one * 3)
  1334. assert_raises(ValueError, geom, bad_p_two * 3)
  1335. def test_hypergeometric(self):
  1336. ngood = [1]
  1337. nbad = [2]
  1338. nsample = [2]
  1339. bad_ngood = [-1]
  1340. bad_nbad = [-2]
  1341. bad_nsample_one = [0]
  1342. bad_nsample_two = [4]
  1343. hypergeom = np.random.hypergeometric
  1344. desired = np.array([1, 1, 1])
  1345. self.setSeed()
  1346. actual = hypergeom(ngood * 3, nbad, nsample)
  1347. assert_array_equal(actual, desired)
  1348. assert_raises(ValueError, hypergeom, bad_ngood * 3, nbad, nsample)
  1349. assert_raises(ValueError, hypergeom, ngood * 3, bad_nbad, nsample)
  1350. assert_raises(ValueError, hypergeom, ngood * 3, nbad, bad_nsample_one)
  1351. assert_raises(ValueError, hypergeom, ngood * 3, nbad, bad_nsample_two)
  1352. self.setSeed()
  1353. actual = hypergeom(ngood, nbad * 3, nsample)
  1354. assert_array_equal(actual, desired)
  1355. assert_raises(ValueError, hypergeom, bad_ngood, nbad * 3, nsample)
  1356. assert_raises(ValueError, hypergeom, ngood, bad_nbad * 3, nsample)
  1357. assert_raises(ValueError, hypergeom, ngood, nbad * 3, bad_nsample_one)
  1358. assert_raises(ValueError, hypergeom, ngood, nbad * 3, bad_nsample_two)
  1359. self.setSeed()
  1360. actual = hypergeom(ngood, nbad, nsample * 3)
  1361. assert_array_equal(actual, desired)
  1362. assert_raises(ValueError, hypergeom, bad_ngood, nbad, nsample * 3)
  1363. assert_raises(ValueError, hypergeom, ngood, bad_nbad, nsample * 3)
  1364. assert_raises(ValueError, hypergeom, ngood, nbad, bad_nsample_one * 3)
  1365. assert_raises(ValueError, hypergeom, ngood, nbad, bad_nsample_two * 3)
  1366. def test_logseries(self):
  1367. p = [0.5]
  1368. bad_p_one = [2]
  1369. bad_p_two = [-1]
  1370. logseries = np.random.logseries
  1371. desired = np.array([1, 1, 1])
  1372. self.setSeed()
  1373. actual = logseries(p * 3)
  1374. assert_array_equal(actual, desired)
  1375. assert_raises(ValueError, logseries, bad_p_one * 3)
  1376. assert_raises(ValueError, logseries, bad_p_two * 3)
  1377. @pytest.mark.skipif(IS_WASM, reason="can't start thread")
  1378. class TestThread:
  1379. # make sure each state produces the same sequence even in threads
  1380. def setup_method(self):
  1381. self.seeds = range(4)
  1382. def check_function(self, function, sz):
  1383. from threading import Thread
  1384. out1 = np.empty((len(self.seeds),) + sz)
  1385. out2 = np.empty((len(self.seeds),) + sz)
  1386. # threaded generation
  1387. t = [Thread(target=function, args=(np.random.RandomState(s), o))
  1388. for s, o in zip(self.seeds, out1)]
  1389. [x.start() for x in t]
  1390. [x.join() for x in t]
  1391. # the same serial
  1392. for s, o in zip(self.seeds, out2):
  1393. function(np.random.RandomState(s), o)
  1394. # these platforms change x87 fpu precision mode in threads
  1395. if np.intp().dtype.itemsize == 4 and sys.platform == "win32":
  1396. assert_array_almost_equal(out1, out2)
  1397. else:
  1398. assert_array_equal(out1, out2)
  1399. def test_normal(self):
  1400. def gen_random(state, out):
  1401. out[...] = state.normal(size=10000)
  1402. self.check_function(gen_random, sz=(10000,))
  1403. def test_exp(self):
  1404. def gen_random(state, out):
  1405. out[...] = state.exponential(scale=np.ones((100, 1000)))
  1406. self.check_function(gen_random, sz=(100, 1000))
  1407. def test_multinomial(self):
  1408. def gen_random(state, out):
  1409. out[...] = state.multinomial(10, [1/6.]*6, size=10000)
  1410. self.check_function(gen_random, sz=(10000, 6))
  1411. # See Issue #4263
  1412. class TestSingleEltArrayInput:
  1413. def setup_method(self):
  1414. self.argOne = np.array([2])
  1415. self.argTwo = np.array([3])
  1416. self.argThree = np.array([4])
  1417. self.tgtShape = (1,)
  1418. def test_one_arg_funcs(self):
  1419. funcs = (np.random.exponential, np.random.standard_gamma,
  1420. np.random.chisquare, np.random.standard_t,
  1421. np.random.pareto, np.random.weibull,
  1422. np.random.power, np.random.rayleigh,
  1423. np.random.poisson, np.random.zipf,
  1424. np.random.geometric, np.random.logseries)
  1425. probfuncs = (np.random.geometric, np.random.logseries)
  1426. for func in funcs:
  1427. if func in probfuncs: # p < 1.0
  1428. out = func(np.array([0.5]))
  1429. else:
  1430. out = func(self.argOne)
  1431. assert_equal(out.shape, self.tgtShape)
  1432. def test_two_arg_funcs(self):
  1433. funcs = (np.random.uniform, np.random.normal,
  1434. np.random.beta, np.random.gamma,
  1435. np.random.f, np.random.noncentral_chisquare,
  1436. np.random.vonmises, np.random.laplace,
  1437. np.random.gumbel, np.random.logistic,
  1438. np.random.lognormal, np.random.wald,
  1439. np.random.binomial, np.random.negative_binomial)
  1440. probfuncs = (np.random.binomial, np.random.negative_binomial)
  1441. for func in funcs:
  1442. if func in probfuncs: # p <= 1
  1443. argTwo = np.array([0.5])
  1444. else:
  1445. argTwo = self.argTwo
  1446. out = func(self.argOne, argTwo)
  1447. assert_equal(out.shape, self.tgtShape)
  1448. out = func(self.argOne[0], argTwo)
  1449. assert_equal(out.shape, self.tgtShape)
  1450. out = func(self.argOne, argTwo[0])
  1451. assert_equal(out.shape, self.tgtShape)
  1452. def test_randint(self):
  1453. itype = [bool, np.int8, np.uint8, np.int16, np.uint16,
  1454. np.int32, np.uint32, np.int64, np.uint64]
  1455. func = np.random.randint
  1456. high = np.array([1])
  1457. low = np.array([0])
  1458. for dt in itype:
  1459. out = func(low, high, dtype=dt)
  1460. assert_equal(out.shape, self.tgtShape)
  1461. out = func(low[0], high, dtype=dt)
  1462. assert_equal(out.shape, self.tgtShape)
  1463. out = func(low, high[0], dtype=dt)
  1464. assert_equal(out.shape, self.tgtShape)
  1465. def test_three_arg_funcs(self):
  1466. funcs = [np.random.noncentral_f, np.random.triangular,
  1467. np.random.hypergeometric]
  1468. for func in funcs:
  1469. out = func(self.argOne, self.argTwo, self.argThree)
  1470. assert_equal(out.shape, self.tgtShape)
  1471. out = func(self.argOne[0], self.argTwo, self.argThree)
  1472. assert_equal(out.shape, self.tgtShape)
  1473. out = func(self.argOne, self.argTwo[0], self.argThree)
  1474. assert_equal(out.shape, self.tgtShape)