test_random.py 68 KB

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