test_random.py 70 KB

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