test_random.py 68 KB

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