/usr/include/d/4.8/std/random.d is in libphobos-4.8-dev 4.8.5-4ubuntu2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 | // Written in the D programming language.
/**
Facilities for random number generation.
The new-style generator objects hold their own state so they are
immune of threading issues. The generators feature a number of
well-known and well-documented methods of generating random
numbers. An overall fast and reliable means to generate random numbers
is the $(D_PARAM Mt19937) generator, which derives its name from
"$(LUCKY Mersenne Twister) with a period of 2 to the power of
19937". In memory-constrained situations, $(LUCKY linear congruential)
generators such as $(D MinstdRand0) and $(D MinstdRand) might be
useful. The standard library provides an alias $(D_PARAM Random) for
whichever generator it considers the most fit for the target
environment.
Example:
----
// Generate a uniformly-distributed integer in the range [0, 14]
auto i = uniform(0, 15);
// Generate a uniformly-distributed real in the range [0, 100$(RPAREN)
// using a specific random generator
Random gen;
auto r = uniform(0.0L, 100.0L, gen);
----
In addition to random number generators, this module features
distributions, which skew a generator's output statistical
distribution in various ways. So far the uniform distribution for
integers and real numbers have been implemented.
Source: $(PHOBOSSRC std/_random.d)
Macros:
WIKI = Phobos/StdRandom
Copyright: Copyright Andrei Alexandrescu 2008 - 2009, Joseph Rushton Wakeling 2012.
License: <a href="http://www.boost.org/LICENSE_1_0.txt">Boost License 1.0</a>.
Authors: $(WEB erdani.org, Andrei Alexandrescu)
Masahiro Nakagawa (Xorshift randome generator)
$(WEB braingam.es, Joseph Rushton Wakeling) (Algorithm D for random sampling)
Credits: The entire random number library architecture is derived from the
excellent $(WEB open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2461.pdf, C++0X)
random number facility proposed by Jens Maurer and contributed to by
researchers at the Fermi laboratory(excluding Xorshift).
*/
/*
Copyright Andrei Alexandrescu 2008 - 2009.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
module std.random;
import std.algorithm, std.c.time, std.conv, std.exception,
std.math, std.numeric, std.range, std.traits,
core.thread, core.time;
import std.string : format;
version(unittest) import std.typetuple;
// Segments of the code in this file Copyright (c) 1997 by Rick Booth
// From "Inner Loops" by Rick Booth, Addison-Wesley
// Work derived from:
/*
A C-program for MT19937, with initialization improved 2002/1/26.
Coded by Takuji Nishimura and Makoto Matsumoto.
Before using, initialize the state by using init_genrand(seed)
or init_by_array(init_key, key_length).
Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The names of its contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Any feedback is very welcome.
http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
*/
/**
* Test if Rng is a random-number generator. The overload
* taking a ElementType also makes sure that the Rng generates
* values of that type.
*
* A random-number generator has at least the following features:
* $(UL
* $(LI it's an InputRange)
* $(LI it has a 'bool isUniformRandom' field readable in CTFE)
* )
*/
template isUniformRNG(Rng, ElementType)
{
enum bool isUniformRNG = isInputRange!Rng &&
is(typeof(Rng.front) == ElementType) &&
is(typeof(
{
static assert(Rng.isUniformRandom); //tag
}));
}
/**
* ditto
*/
template isUniformRNG(Rng)
{
enum bool isUniformRNG = isInputRange!Rng &&
is(typeof(
{
static assert(Rng.isUniformRandom); //tag
}));
}
/**
* Test if Rng is seedable. The overload
* taking a SeedType also makes sure that the Rng can be seeded with SeedType.
*
* A seedable random-number generator has the following additional features:
* $(UL
* $(LI it has a 'seed(ElementType)' function)
* )
*/
template isSeedable(Rng, SeedType)
{
enum bool isSeedable = isUniformRNG!(Rng) &&
is(typeof(
{
Rng r = void; // can define a Rng object
r.seed(SeedType.init); // can seed a Rng
}));
}
///ditto
template isSeedable(Rng)
{
enum bool isSeedable = isUniformRNG!Rng &&
is(typeof(
{
Rng r = void; // can define a Rng object
r.seed(typeof(r.front).init); // can seed a Rng
}));
}
unittest
{
struct NoRng
{
@property uint front() {return 0;}
@property bool empty() {return false;}
void popFront() {}
}
static assert(!isUniformRNG!(NoRng, uint));
static assert(!isUniformRNG!(NoRng));
static assert(!isSeedable!(NoRng, uint));
static assert(!isSeedable!(NoRng));
struct NoRng2
{
@property uint front() {return 0;}
@property bool empty() {return false;}
void popFront() {}
enum isUniformRandom = false;
}
static assert(!isUniformRNG!(NoRng2, uint));
static assert(!isUniformRNG!(NoRng2));
static assert(!isSeedable!(NoRng2, uint));
static assert(!isSeedable!(NoRng2));
struct NoRng3
{
@property bool empty() {return false;}
void popFront() {}
enum isUniformRandom = true;
}
static assert(!isUniformRNG!(NoRng3, uint));
static assert(!isUniformRNG!(NoRng3));
static assert(!isSeedable!(NoRng3, uint));
static assert(!isSeedable!(NoRng3));
struct validRng
{
@property uint front() {return 0;}
@property bool empty() {return false;}
void popFront() {}
enum isUniformRandom = true;
}
static assert(isUniformRNG!(validRng, uint));
static assert(isUniformRNG!(validRng));
static assert(!isSeedable!(validRng, uint));
static assert(!isSeedable!(validRng));
struct seedRng
{
@property uint front() {return 0;}
@property bool empty() {return false;}
void popFront() {}
void seed(uint val){}
enum isUniformRandom = true;
}
static assert(isUniformRNG!(seedRng, uint));
static assert(isUniformRNG!(seedRng));
static assert(isSeedable!(seedRng, uint));
static assert(isSeedable!(seedRng));
}
/**
Linear Congruential generator.
*/
struct LinearCongruentialEngine(UIntType, UIntType a, UIntType c, UIntType m)
if(isUnsigned!UIntType)
{
///Mark this as a Rng
enum bool isUniformRandom = true;
/// Does this generator have a fixed range? ($(D_PARAM true)).
enum bool hasFixedRange = true;
/// Lowest generated value ($(D 1) if $(D c == 0), $(D 0) otherwise).
enum UIntType min = ( c == 0 ? 1 : 0 );
/// Highest generated value ($(D modulus - 1)).
enum UIntType max = m - 1;
/**
The parameters of this distribution. The random number is $(D_PARAM x
= (x * multipler + increment) % modulus).
*/
enum UIntType multiplier = a;
///ditto
enum UIntType increment = c;
///ditto
enum UIntType modulus = m;
static assert(isIntegral!(UIntType));
static assert(m == 0 || a < m);
static assert(m == 0 || c < m);
static assert(m == 0 ||
(cast(ulong)a * (m-1) + c) % m == (c < a ? c - a + m : c - a));
// Check for maximum range
private static ulong gcd(ulong a, ulong b)
{
while (b)
{
auto t = b;
b = a % b;
a = t;
}
return a;
}
private static ulong primeFactorsOnly(ulong n)
{
ulong result = 1;
ulong iter = 2;
for (; n >= iter * iter; iter += 2 - (iter == 2))
{
if (n % iter) continue;
result *= iter;
do
{
n /= iter;
} while (n % iter == 0);
}
return result * n;
}
unittest
{
static assert(primeFactorsOnly(100) == 10);
//writeln(primeFactorsOnly(11));
static assert(primeFactorsOnly(11) == 11);
static assert(primeFactorsOnly(7 * 7 * 7 * 11 * 15 * 11) == 7 * 11 * 15);
static assert(primeFactorsOnly(129 * 2) == 129 * 2);
// enum x = primeFactorsOnly(7 * 7 * 7 * 11 * 15);
// static assert(x == 7 * 11 * 15);
}
private static bool properLinearCongruentialParameters(ulong m,
ulong a, ulong c)
{
if (m == 0)
{
static if (is(UIntType == uint))
{
// Assume m is uint.max + 1
m = (1uL << 32);
}
else
{
return false;
}
}
// Bounds checking
if (a == 0 || a >= m || c >= m) return false;
// c and m are relatively prime
if (c > 0 && gcd(c, m) != 1) return false;
// a - 1 is divisible by all prime factors of m
if ((a - 1) % primeFactorsOnly(m)) return false;
// if a - 1 is multiple of 4, then m is a multiple of 4 too.
if ((a - 1) % 4 == 0 && m % 4) return false;
// Passed all tests
return true;
}
// check here
static assert(c == 0 || properLinearCongruentialParameters(m, a, c),
"Incorrect instantiation of LinearCongruentialEngine");
/**
Constructs a $(D_PARAM LinearCongruentialEngine) generator seeded with
$(D x0).
*/
this(UIntType x0)
{
seed(x0);
}
/**
(Re)seeds the generator.
*/
void seed(UIntType x0 = 1)
{
static if (c == 0)
{
enforce(x0, "Invalid (zero) seed for "
~ LinearCongruentialEngine.stringof);
}
_x = modulus ? (x0 % modulus) : x0;
popFront();
}
/**
Advances the random sequence.
*/
void popFront()
{
static if (m)
{
static if (is(UIntType == uint) && m == uint.max)
{
immutable ulong
x = (cast(ulong) a * _x + c),
v = x >> 32,
w = x & uint.max;
immutable y = cast(uint)(v + w);
_x = (y < v || y == uint.max) ? (y + 1) : y;
}
else static if (is(UIntType == uint) && m == int.max)
{
immutable ulong
x = (cast(ulong) a * _x + c),
v = x >> 31,
w = x & int.max;
immutable uint y = cast(uint)(v + w);
_x = (y >= int.max) ? (y - int.max) : y;
}
else
{
_x = cast(UIntType) ((cast(ulong) a * _x + c) % m);
}
}
else
{
_x = a * _x + c;
}
}
/**
Returns the current number in the random sequence.
*/
@property UIntType front()
{
return _x;
}
///
@property typeof(this) save()
{
return this;
}
/**
Always $(D false) (random generators are infinite ranges).
*/
enum bool empty = false;
/**
Compares against $(D_PARAM rhs) for equality.
*/
bool opEquals(ref const LinearCongruentialEngine rhs) const
{
return _x == rhs._x;
}
private UIntType _x = m ? (a + c) % m : (a + c);
}
/**
Define $(D_PARAM LinearCongruentialEngine) generators with well-chosen
parameters. $(D MinstdRand0) implements Park and Miller's "minimal
standard" $(WEB
wikipedia.org/wiki/Park%E2%80%93Miller_random_number_generator,
generator) that uses 16807 for the multiplier. $(D MinstdRand)
implements a variant that has slightly better spectral behavior by
using the multiplier 48271. Both generators are rather simplistic.
Example:
----
// seed with a constant
auto rnd0 = MinstdRand0(1);
auto n = rnd0.front; // same for each run
// Seed with an unpredictable value
rnd0.seed(unpredictableSeed);
n = rnd0.front; // different across runs
----
*/
alias LinearCongruentialEngine!(uint, 16807, 0, 2147483647) MinstdRand0;
/// ditto
alias LinearCongruentialEngine!(uint, 48271, 0, 2147483647) MinstdRand;
unittest
{
static assert(isForwardRange!MinstdRand);
static assert(isUniformRNG!MinstdRand);
static assert(isUniformRNG!MinstdRand0);
static assert(isUniformRNG!(MinstdRand, uint));
static assert(isUniformRNG!(MinstdRand0, uint));
static assert(isSeedable!MinstdRand);
static assert(isSeedable!MinstdRand0);
static assert(isSeedable!(MinstdRand, uint));
static assert(isSeedable!(MinstdRand0, uint));
// The correct numbers are taken from The Database of Integer Sequences
// http://www.research.att.com/~njas/sequences/eisBTfry00128.txt
auto checking0 = [
16807UL,282475249,1622650073,984943658,1144108930,470211272,
101027544,1457850878,1458777923,2007237709,823564440,1115438165,
1784484492,74243042,114807987,1137522503,1441282327,16531729,
823378840,143542612 ];
//auto rnd0 = MinstdRand0(1);
MinstdRand0 rnd0;
foreach (e; checking0)
{
assert(rnd0.front == e);
rnd0.popFront();
}
// Test the 10000th invocation
// Correct value taken from:
// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2461.pdf
rnd0.seed();
popFrontN(rnd0, 9999);
assert(rnd0.front == 1043618065);
// Test MinstdRand
auto checking = [48271UL,182605794,1291394886,1914720637,2078669041,
407355683];
//auto rnd = MinstdRand(1);
MinstdRand rnd;
foreach (e; checking)
{
assert(rnd.front == e);
rnd.popFront();
}
// Test the 10000th invocation
// Correct value taken from:
// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2461.pdf
rnd.seed();
popFrontN(rnd, 9999);
assert(rnd.front == 399268537);
// Check .save works
foreach (Type; TypeTuple!(MinstdRand0, MinstdRand))
{
auto rnd1 = Type(unpredictableSeed);
auto rnd2 = rnd1.save;
assert(rnd1 == rnd2);
// Enable next test when RNGs are reference types
version(none) { assert(rnd1 !is rnd2); }
assert(rnd1.take(100).array() == rnd2.take(100).array());
}
}
/**
The $(LUCKY Mersenne Twister) generator.
*/
struct MersenneTwisterEngine(UIntType, size_t w, size_t n, size_t m, size_t r,
UIntType a, size_t u, size_t s,
UIntType b, size_t t,
UIntType c, size_t l)
if(isUnsigned!UIntType)
{
///Mark this as a Rng
enum bool isUniformRandom = true;
/**
Parameter for the generator.
*/
enum size_t wordSize = w;
enum size_t stateSize = n;
enum size_t shiftSize = m;
enum size_t maskBits = r;
enum UIntType xorMask = a;
enum UIntType temperingU = u;
enum size_t temperingS = s;
enum UIntType temperingB = b;
enum size_t temperingT = t;
enum UIntType temperingC = c;
enum size_t temperingL = l;
/// Smallest generated value (0).
enum UIntType min = 0;
/// Largest generated value.
enum UIntType max =
w == UIntType.sizeof * 8 ? UIntType.max : (1u << w) - 1;
/// The default seed value.
enum UIntType defaultSeed = 5489u;
static assert(1 <= m && m <= n);
static assert(0 <= r && 0 <= u && 0 <= s && 0 <= t && 0 <= l);
static assert(r <= w && u <= w && s <= w && t <= w && l <= w);
static assert(0 <= a && 0 <= b && 0 <= c);
static assert(a <= max && b <= max && c <= max);
/**
Constructs a MersenneTwisterEngine object.
*/
this(UIntType value)
{
seed(value);
}
/**
Seeds a MersenneTwisterEngine object.
Note:
This seed function gives 2^32 starting points. To allow the RNG to be started in any one of its
internal states use the seed overload taking an InputRange.
*/
void seed()(UIntType value = defaultSeed)
{
static if (w == UIntType.sizeof * 8)
{
mt[0] = value;
}
else
{
static assert(max + 1 > 0);
mt[0] = value % (max + 1);
}
for (mti = 1; mti < n; ++mti)
{
mt[mti] =
cast(UIntType)
(1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> (w - 2))) + mti);
/* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
/* In the previous versions, MSBs of the seed affect */
/* only MSBs of the array mt[]. */
/* 2002/01/09 modified by Makoto Matsumoto */
//mt[mti] &= ResultType.max;
/* for >32 bit machines */
}
popFront();
}
/**
Seeds a MersenneTwisterEngine object using an InputRange.
Throws:
$(D Exception) if the InputRange didn't provide enough elements to seed the generator.
The number of elements required is the 'n' template parameter of the MersenneTwisterEngine struct.
Examples:
----------------
Mt19937 gen;
gen.seed(map!((a) => unpredictableSeed)(repeat(0)));
----------------
*/
void seed(T)(T range) if(isInputRange!T && is(Unqual!(ElementType!T) == UIntType))
{
size_t j;
for(j = 0; j < n && !range.empty; ++j, range.popFront())
{
mt[j] = range.front;
}
mti = n;
if(range.empty && j < n)
{
throw new Exception(format("MersenneTwisterEngine.seed: Input range didn't provide enough"
" elements: Need %s elemnets.", n));
}
popFront();
}
/**
Advances the generator.
*/
void popFront()
{
if (mti == size_t.max) seed();
enum UIntType
upperMask = ~((cast(UIntType) 1u <<
(UIntType.sizeof * 8 - (w - r))) - 1),
lowerMask = (cast(UIntType) 1u << r) - 1;
static immutable UIntType[2] mag01 = [0x0UL, a];
ulong y = void;
if (mti >= n)
{
/* generate N words at one time */
int kk = 0;
const limit1 = n - m;
for (; kk < limit1; ++kk)
{
y = (mt[kk] & upperMask)|(mt[kk + 1] & lowerMask);
mt[kk] = cast(UIntType) (mt[kk + m] ^ (y >> 1)
^ mag01[cast(UIntType) y & 0x1U]);
}
const limit2 = n - 1;
for (; kk < limit2; ++kk)
{
y = (mt[kk] & upperMask)|(mt[kk + 1] & lowerMask);
mt[kk] = cast(UIntType) (mt[kk + (m -n)] ^ (y >> 1)
^ mag01[cast(UIntType) y & 0x1U]);
}
y = (mt[n -1] & upperMask)|(mt[0] & lowerMask);
mt[n - 1] = cast(UIntType) (mt[m - 1] ^ (y >> 1)
^ mag01[cast(UIntType) y & 0x1U]);
mti = 0;
}
y = mt[mti++];
/* Tempering */
y ^= (y >> temperingU);
y ^= (y << temperingS) & temperingB;
y ^= (y << temperingT) & temperingC;
y ^= (y >> temperingL);
_y = cast(UIntType) y;
}
/**
Returns the current random value.
*/
@property UIntType front()
{
if (mti == size_t.max) seed();
return _y;
}
///
@property typeof(this) save()
{
return this;
}
/**
Always $(D false).
*/
enum bool empty = false;
private UIntType[n] mt;
private size_t mti = size_t.max; /* means mt is not initialized */
UIntType _y = UIntType.max;
}
/**
A $(D MersenneTwisterEngine) instantiated with the parameters of the
original engine $(WEB math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html,
MT19937), generating uniformly-distributed 32-bit numbers with a
period of 2 to the power of 19937. Recommended for random number
generation unless memory is severely restricted, in which case a $(D
LinearCongruentialEngine) would be the generator of choice.
Example:
----
// seed with a constant
Mt19937 gen;
auto n = gen.front; // same for each run
// Seed with an unpredictable value
gen.seed(unpredictableSeed);
n = gen.front; // different across runs
----
*/
alias MersenneTwisterEngine!(uint, 32, 624, 397, 31, 0x9908b0df, 11, 7,
0x9d2c5680, 15, 0xefc60000, 18)
Mt19937;
unittest
{
static assert(isUniformRNG!Mt19937);
static assert(isUniformRNG!(Mt19937, uint));
static assert(isSeedable!Mt19937);
static assert(isSeedable!(Mt19937, uint));
static assert(isSeedable!(Mt19937, typeof(map!((a) => unpredictableSeed)(repeat(0)))));
Mt19937 gen;
popFrontN(gen, 9999);
assert(gen.front == 4123659995);
}
unittest
{
Mt19937 gen;
assertThrown(gen.seed(map!((a) => unpredictableSeed)(repeat(0, 623))));
gen.seed(map!((a) => unpredictableSeed)(repeat(0, 624)));
//infinite Range
gen.seed(map!((a) => unpredictableSeed)(repeat(0)));
}
unittest
{
uint a, b;
{
Mt19937 gen;
a = gen.front;
}
{
Mt19937 gen;
gen.popFront();
//popFrontN(gen, 1); // skip 1 element
b = gen.front;
}
assert(a != b);
}
unittest
{
// Check .save works
foreach(Type; TypeTuple!(Mt19937))
{
auto gen1 = Type(unpredictableSeed);
auto gen2 = gen1.save;
assert(gen1 == gen2); // Danger, Will Robinson -- no opEquals for MT
// Enable next test when RNGs are reference types
version(none) { assert(gen1 !is gen2); }
assert(gen1.take(100).array() == gen2.take(100).array());
}
}
/**
* Xorshift generator using 32bit algorithm.
*
* Implemented according to $(WEB www.jstatsoft.org/v08/i14/paper, Xorshift RNGs).
*
* $(BOOKTABLE $(TEXTWITHCOMMAS Supporting bits are below, $(D bits) means second parameter of XorshiftEngine.),
* $(TR $(TH bits) $(TH period))
* $(TR $(TD 32) $(TD 2^32 - 1))
* $(TR $(TD 64) $(TD 2^64 - 1))
* $(TR $(TD 96) $(TD 2^96 - 1))
* $(TR $(TD 128) $(TD 2^128 - 1))
* $(TR $(TD 160) $(TD 2^160 - 1))
* $(TR $(TD 192) $(TD 2^192 - 2^32))
* )
*/
struct XorshiftEngine(UIntType, UIntType bits, UIntType a, UIntType b, UIntType c)
if(isUnsigned!UIntType)
{
static assert(bits == 32 || bits == 64 || bits == 96 || bits == 128 || bits == 160 || bits == 192,
"Xorshift supports only 32, 64, 96, 128, 160 and 192 bit versions. "
~ to!string(bits) ~ " is not supported.");
public:
///Mark this as a Rng
enum bool isUniformRandom = true;
/// Always $(D false) (random generators are infinite ranges).
enum empty = false;
/// Smallest generated value.
enum UIntType min = 0;
/// Largest generated value.
enum UIntType max = UIntType.max;
private:
enum size = bits / 32;
static if (bits == 32)
UIntType[size] seeds_ = [2463534242];
else static if (bits == 64)
UIntType[size] seeds_ = [123456789, 362436069];
else static if (bits == 96)
UIntType[size] seeds_ = [123456789, 362436069, 521288629];
else static if (bits == 128)
UIntType[size] seeds_ = [123456789, 362436069, 521288629, 88675123];
else static if (bits == 160)
UIntType[size] seeds_ = [123456789, 362436069, 521288629, 88675123, 5783321];
else static if (bits == 192)
{
UIntType[size] seeds_ = [123456789, 362436069, 521288629, 88675123, 5783321, 6615241];
UIntType value_;
}
else
{
static assert(false, "Phobos Error: Xorshift has no instantiation rule for "
~ to!string(bits) ~ " bits.");
}
public:
/**
* Constructs a $(D XorshiftEngine) generator seeded with $(D_PARAM x0).
*/
@safe
this(UIntType x0)
{
seed(x0);
}
/**
* (Re)seeds the generator.
*/
@safe
nothrow void seed(UIntType x0)
{
// Initialization routine from MersenneTwisterEngine.
foreach (i, e; seeds_)
seeds_[i] = x0 = cast(UIntType)(1812433253U * (x0 ^ (x0 >> 30)) + i + 1);
// All seeds must not be 0.
sanitizeSeeds(seeds_);
popFront();
}
/**
* Returns the current number in the random sequence.
*/
@property @safe
nothrow UIntType front()
{
static if (bits == 192)
return value_;
else
return seeds_[size - 1];
}
/**
* Advances the random sequence.
*/
@safe
nothrow void popFront()
{
UIntType temp;
static if (bits == 32)
{
temp = seeds_[0] ^ (seeds_[0] << a);
temp = temp ^ (temp >> b);
seeds_[0] = temp ^ (temp << c);
}
else static if (bits == 64)
{
temp = seeds_[0] ^ (seeds_[0] << a);
seeds_[0] = seeds_[1];
seeds_[1] = seeds_[1] ^ (seeds_[1] >> c) ^ temp ^ (temp >> b);
}
else static if (bits == 96)
{
temp = seeds_[0] ^ (seeds_[0] << a);
seeds_[0] = seeds_[1];
seeds_[1] = seeds_[2];
seeds_[2] = seeds_[2] ^ (seeds_[2] >> c) ^ temp ^ (temp >> b);
}
else static if (bits == 128)
{
temp = seeds_[0] ^ (seeds_[0] << a);
seeds_[0] = seeds_[1];
seeds_[1] = seeds_[2];
seeds_[2] = seeds_[3];
seeds_[3] = seeds_[3] ^ (seeds_[3] >> c) ^ temp ^ (temp >> b);
}
else static if (bits == 160)
{
temp = seeds_[0] ^ (seeds_[0] << a);
seeds_[0] = seeds_[1];
seeds_[1] = seeds_[2];
seeds_[2] = seeds_[3];
seeds_[3] = seeds_[4];
seeds_[4] = seeds_[4] ^ (seeds_[4] >> c) ^ temp ^ (temp >> b);
}
else static if (bits == 192)
{
temp = seeds_[0] ^ (seeds_[0] >> a);
seeds_[0] = seeds_[1];
seeds_[1] = seeds_[2];
seeds_[2] = seeds_[3];
seeds_[3] = seeds_[4];
seeds_[4] = seeds_[4] ^ (seeds_[4] << c) ^ temp ^ (temp << b);
value_ = seeds_[4] + (seeds_[5] += 362437);
}
else
{
static assert(false, "Phobos Error: Xorshift has no popFront() update for "
~ to!string(bits) ~ " bits.");
}
}
/**
* Captures a range state.
*/
@property
typeof(this) save()
{
return this;
}
/**
* Compares against $(D_PARAM rhs) for equality.
*/
@safe
nothrow bool opEquals(ref const XorshiftEngine rhs) const
{
return seeds_ == rhs.seeds_;
}
private:
@safe
static nothrow void sanitizeSeeds(ref UIntType[size] seeds)
{
for (uint i; i < seeds.length; i++)
{
if (seeds[i] == 0)
seeds[i] = i + 1;
}
}
unittest
{
static if (size == 4) // Other bits too
{
UIntType[size] seeds = [1, 0, 0, 4];
sanitizeSeeds(seeds);
assert(seeds == [1, 2, 3, 4]);
}
}
}
/**
* Define $(D XorshiftEngine) generators with well-chosen parameters. See each bits examples of "Xorshift RNGs".
* $(D Xorshift) is a Xorshift128's alias because 128bits implementation is mostly used.
*
* Example:
* -----
* // Seed with a constant
* auto rnd = Xorshift(1);
* auto num = rnd.front; // same for each run
*
* // Seed with an unpredictable value
* rnd.seed(unpredictableSeed());
* num = rnd.front; // different across runs
* -----
*/
alias XorshiftEngine!(uint, 32, 13, 17, 15) Xorshift32;
alias XorshiftEngine!(uint, 64, 10, 13, 10) Xorshift64; /// ditto
alias XorshiftEngine!(uint, 96, 10, 5, 26) Xorshift96; /// ditto
alias XorshiftEngine!(uint, 128, 11, 8, 19) Xorshift128; /// ditto
alias XorshiftEngine!(uint, 160, 2, 1, 4) Xorshift160; /// ditto
alias XorshiftEngine!(uint, 192, 2, 1, 4) Xorshift192; /// ditto
alias Xorshift128 Xorshift; /// ditto
unittest
{
static assert(isForwardRange!Xorshift);
static assert(isUniformRNG!Xorshift);
static assert(isUniformRNG!(Xorshift, uint));
static assert(isSeedable!Xorshift);
static assert(isSeedable!(Xorshift, uint));
// Result from reference implementation.
auto checking = [
[2463534242UL, 901999875, 3371835698, 2675058524, 1053936272, 3811264849, 472493137, 3856898176, 2131710969, 2312157505],
[362436069UL, 2113136921, 19051112, 3010520417, 951284840, 1213972223, 3173832558, 2611145638, 2515869689, 2245824891],
[521288629UL, 1950277231, 185954712, 1582725458, 3580567609, 2303633688, 2394948066, 4108622809, 1116800180, 3357585673],
[88675123UL, 3701687786, 458299110, 2500872618, 3633119408, 516391518, 2377269574, 2599949379, 717229868, 137866584],
[5783321UL, 393427209, 1947109840, 565829276, 1006220149, 971147905, 1436324242, 2800460115, 1484058076, 3823330032],
[0UL, 246875399, 3690007200, 1264581005, 3906711041, 1866187943, 2481925219, 2464530826, 1604040631, 3653403911]
];
alias TypeTuple!(Xorshift32, Xorshift64, Xorshift96, Xorshift128, Xorshift160, Xorshift192) XorshiftTypes;
foreach (I, Type; XorshiftTypes)
{
Type rnd;
foreach (e; checking[I])
{
assert(rnd.front == e);
rnd.popFront();
}
}
// Check .save works
foreach (Type; XorshiftTypes)
{
auto rnd1 = Type(unpredictableSeed);
auto rnd2 = rnd1.save;
assert(rnd1 == rnd2);
// Enable next test when RNGs are reference types
version(none) { assert(rnd1 !is rnd2); }
assert(rnd1.take(100).array() == rnd2.take(100).array());
}
}
/* A complete list of all pseudo-random number generators implemented in
* std.random. This can be used to confirm that a given function or
* object is compatible with all the pseudo-random number generators
* available. It is enabled only in unittest mode.
*
* Example:
*
* ----
* foreach(Rng; PseudoRngTypes)
* {
* static assert(isUniformRng!Rng);
* auto rng = Rng(unpredictableSeed);
* foo(rng);
* }
* ----
*/
version(unittest)
{
package alias PseudoRngTypes = TypeTuple!(MinstdRand0, MinstdRand, Mt19937, Xorshift32, Xorshift64,
Xorshift96, Xorshift128, Xorshift160, Xorshift192);
}
unittest
{
foreach(Rng; PseudoRngTypes)
{
static assert(isUniformRNG!Rng);
}
}
/**
A "good" seed for initializing random number engines. Initializing
with $(D_PARAM unpredictableSeed) makes engines generate different
random number sequences every run.
Example:
----
auto rnd = Random(unpredictableSeed);
auto n = rnd.front;
...
----
*/
@property uint unpredictableSeed()
{
static bool seeded;
static MinstdRand0 rand;
if (!seeded)
{
uint threadID = cast(uint) cast(void*) Thread.getThis();
rand.seed((getpid() + threadID) ^ cast(uint) TickDuration.currSystemTick.length);
seeded = true;
}
rand.popFront();
return cast(uint) (TickDuration.currSystemTick.length ^ rand.front);
}
unittest
{
// not much to test here
auto a = unpredictableSeed;
static assert(is(typeof(a) == uint));
}
/**
The "default", "favorite", "suggested" random number generator type on
the current platform. It is an alias for one of the previously-defined
generators. You may want to use it if (1) you need to generate some
nice random numbers, and (2) you don't care for the minutiae of the
method being used.
*/
alias Mt19937 Random;
unittest
{
static assert(isUniformRNG!Random);
static assert(isUniformRNG!(Random, uint));
static assert(isSeedable!Random);
static assert(isSeedable!(Random, uint));
}
/**
Global random number generator used by various functions in this
module whenever no generator is specified. It is allocated per-thread
and initialized to an unpredictable value for each thread.
*/
@property ref Random rndGen()
{
static Random result;
static bool initialized;
if (!initialized)
{
static if(isSeedable!(Random, typeof(map!((a) => unpredictableSeed)(repeat(0)))))
result.seed(map!((a) => unpredictableSeed)(repeat(0)));
else
result = Random(unpredictableSeed);
initialized = true;
}
return result;
}
/**
Generates a number between $(D a) and $(D b). The $(D boundaries)
parameter controls the shape of the interval (open vs. closed on
either side). Valid values for $(D boundaries) are $(D "[]"), $(D
"$(LPAREN)]"), $(D "[$(RPAREN)"), and $(D "()"). The default interval
is closed to the left and open to the right. The version that does not
take $(D urng) uses the default generator $(D rndGen).
Example:
----
auto gen = Random(unpredictableSeed);
// Generate an integer in [0, 1023]
auto a = uniform(0, 1024, gen);
// Generate a float in [0, 1$(RPAREN)
auto a = uniform(0.0f, 1.0f, gen);
----
*/
auto uniform(string boundaries = "[)", T1, T2)
(T1 a, T2 b) if (!is(CommonType!(T1, T2) == void))
{
return uniform!(boundaries, T1, T2, Random)(a, b, rndGen);
}
unittest
{
MinstdRand0 gen;
foreach (i; 0 .. 20)
{
auto x = uniform(0.0, 15.0, gen);
assert(0 <= x && x < 15);
}
foreach (i; 0 .. 20)
{
auto x = uniform!"[]"('a', 'z', gen);
assert('a' <= x && x <= 'z');
}
foreach (i; 0 .. 20)
{
auto x = uniform('a', 'z', gen);
assert('a' <= x && x < 'z');
}
foreach(i; 0 .. 20)
{
immutable ubyte a = 0;
immutable ubyte b = 15;
auto x = uniform(a, b, gen);
assert(a <= x && x < b);
}
}
// Implementation of uniform for floating-point types
/// ditto
auto uniform(string boundaries = "[)",
T1, T2, UniformRandomNumberGenerator)
(T1 a, T2 b, ref UniformRandomNumberGenerator urng)
if (isFloatingPoint!(CommonType!(T1, T2)))
{
alias Unqual!(CommonType!(T1, T2)) NumberType;
static if (boundaries[0] == '(')
{
NumberType _a = nextafter(cast(NumberType) a, NumberType.infinity);
}
else
{
NumberType _a = a;
}
static if (boundaries[1] == ')')
{
NumberType _b = nextafter(cast(NumberType) b, -NumberType.infinity);
}
else
{
NumberType _b = b;
}
enforce(_a <= _b,
text("std.random.uniform(): invalid bounding interval ",
boundaries[0], a, ", ", b, boundaries[1]));
NumberType result =
_a + (_b - _a) * cast(NumberType) (urng.front - urng.min)
/ (urng.max - urng.min);
urng.popFront();
return result;
}
// Implementation of uniform for integral types
auto uniform(string boundaries = "[)",
T1, T2, UniformRandomNumberGenerator)
(T1 a, T2 b, ref UniformRandomNumberGenerator urng)
if (isIntegral!(CommonType!(T1, T2)) || isSomeChar!(CommonType!(T1, T2)))
{
alias Unqual!(CommonType!(T1, T2)) ResultType;
// We handle the case "[)' as the common case, and we adjust all
// other cases to fit it.
static if (boundaries[0] == '(')
{
enforce(cast(ResultType) a < ResultType.max,
text("std.random.uniform(): invalid left bound ", a));
ResultType min = cast(ResultType) a + 1;
}
else
{
ResultType min = a;
}
static if (boundaries[1] == ']')
{
enforce(min <= cast(ResultType) b,
text("std.random.uniform(): invalid bounding interval ",
boundaries[0], a, ", ", b, boundaries[1]));
if (b == ResultType.max && min == ResultType.min)
{
// Special case - all bits are occupied
return .uniform!ResultType(urng);
}
auto count = unsigned(b - min) + 1u;
static assert(count.min == 0);
}
else
{
enforce(min < cast(ResultType) b,
text("std.random.uniform(): invalid bounding interval ",
boundaries[0], a, ", ", b, boundaries[1]));
auto count = unsigned(b - min);
static assert(count.min == 0);
}
assert(count != 0);
if (count == 1) return min;
alias typeof(count) CountType;
static assert(CountType.min == 0);
auto bucketSize = 1u + (CountType.max - count + 1) / count;
CountType r;
do
{
r = cast(CountType) (uniform!CountType(urng) / bucketSize);
}
while (r >= count);
return cast(typeof(return)) (min + r);
}
unittest
{
auto gen = Mt19937(unpredictableSeed);
static assert(isForwardRange!(typeof(gen)));
auto a = uniform(0, 1024, gen);
assert(0 <= a && a <= 1024);
auto b = uniform(0.0f, 1.0f, gen);
assert(0 <= b && b < 1, to!string(b));
auto c = uniform(0.0, 1.0);
assert(0 <= c && c < 1);
foreach(T; TypeTuple!(char, wchar, dchar, byte, ubyte, short, ushort,
int, uint, long, ulong, float, double, real))
{
T lo = 0, hi = 100;
T init = uniform(lo, hi);
size_t i = 50;
while (--i && uniform(lo, hi) == init) {}
assert(i > 0);
}
}
/**
Generates a uniformly-distributed number in the range $(D [T.min,
T.max]) for any integral type $(D T). If no random number generator is
passed, uses the default $(D rndGen).
*/
auto uniform(T, UniformRandomNumberGenerator)
(ref UniformRandomNumberGenerator urng)
if (!is(T == enum) && (isIntegral!T || isSomeChar!T))
{
auto r = urng.front;
urng.popFront();
static if (T.sizeof <= r.sizeof)
{
return cast(T) r;
}
else
{
static assert(T.sizeof == 8 && r.sizeof == 4);
T r1 = urng.front | (cast(T)r << 32);
urng.popFront();
return r1;
}
}
/// Ditto
auto uniform(T)()
if (!is(T == enum) && (isIntegral!T || isSomeChar!T))
{
return uniform!T(rndGen);
}
unittest
{
foreach(T; TypeTuple!(char, wchar, dchar, byte, ubyte, short, ushort,
int, uint, long, ulong))
{
T init = uniform!T();
size_t i = 50;
while (--i && uniform!T() == init) {}
assert(i > 0);
}
}
/**
Returns a uniformly selected member of enum $(D E). If no random number
generator is passed, uses the default $(D rndGen).
*/
auto uniform(E, UniformRandomNumberGenerator)
(ref UniformRandomNumberGenerator urng)
if (is(E == enum))
{
static immutable E[EnumMembers!E.length] members = [EnumMembers!E];
return members[std.random.uniform(0, members.length, urng)];
}
/// Ditto
auto uniform(E)()
if (is(E == enum))
{
return uniform!E(rndGen);
}
unittest
{
enum Fruit { Apple = 12, Mango = 29, Pear = 72 }
foreach (_; 0 .. 100)
{
foreach(f; [uniform!Fruit(), rndGen.uniform!Fruit()])
{
assert(f == Fruit.Apple || f == Fruit.Mango || f == Fruit.Pear);
}
}
}
/**
Generates a uniform probability distribution of size $(D n), i.e., an
array of size $(D n) of positive numbers of type $(D F) that sum to
$(D 1). If $(D useThis) is provided, it is used as storage.
*/
F[] uniformDistribution(F = double)(size_t n, F[] useThis = null)
if(isFloatingPoint!F)
{
useThis.length = n;
foreach (ref e; useThis)
{
e = uniform(0.0, 1);
}
normalize(useThis);
return useThis;
}
unittest
{
static assert(is(CommonType!(double, int) == double));
auto a = uniformDistribution(5);
enforce(a.length == 5);
enforce(approxEqual(reduce!"a + b"(a), 1));
a = uniformDistribution(10, a);
enforce(a.length == 10);
enforce(approxEqual(reduce!"a + b"(a), 1));
}
/**
Shuffles elements of $(D r) using $(D gen) as a shuffler. $(D r) must be
a random-access range with length.
*/
void randomShuffle(Range, RandomGen)(Range r, ref RandomGen gen)
if(isRandomAccessRange!Range && isUniformRNG!RandomGen)
{
return partialShuffle!(Range, RandomGen)(r, r.length, gen);
}
/// ditto
void randomShuffle(Range)(Range r)
if(isRandomAccessRange!Range)
{
return randomShuffle(r, rndGen);
}
unittest
{
foreach(Rng; PseudoRngTypes)
{
static assert(isUniformRNG!Rng);
// Also tests partialShuffle indirectly.
auto a = ([ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]).dup;
auto b = a.dup;
Rng gen;
randomShuffle(a, gen);
assert(a.sort == b.sort);
randomShuffle(a);
assert(a.sort == b.sort);
}
}
/**
Partially shuffles the elements of $(D r) such that upon returning $(D r[0..n])
is a random subset of $(D r) and is randomly ordered. $(D r[n..r.length])
will contain the elements not in $(D r[0..n]). These will be in an undefined
order, but will not be random in the sense that their order after
$(D partialShuffle) returns will not be independent of their order before
$(D partialShuffle) was called.
$(D r) must be a random-access range with length. $(D n) must be less than
or equal to $(D r.length).
*/
void partialShuffle(Range, RandomGen)(Range r, size_t n, ref RandomGen gen)
if(isRandomAccessRange!Range && isUniformRNG!RandomGen)
{
enforce(n <= r.length, "n must be <= r.length for partialShuffle.");
foreach (i; 0 .. n)
{
swapAt(r, i, i + uniform(0, r.length - i, gen));
}
}
/// ditto
void partialShuffle(Range)(Range r, size_t n)
if(isRandomAccessRange!Range)
{
return partialShuffle(r, n, rndGen);
}
/**
Rolls a dice with relative probabilities stored in $(D
proportions). Returns the index in $(D proportions) that was chosen.
Example:
----
auto x = dice(0.5, 0.5); // x is 0 or 1 in equal proportions
auto y = dice(50, 50); // y is 0 or 1 in equal proportions
auto z = dice(70, 20, 10); // z is 0 70% of the time, 1 20% of the time,
// and 2 10% of the time
----
*/
size_t dice(Rng, Num)(ref Rng rnd, Num[] proportions...)
if (isNumeric!Num && isForwardRange!Rng)
{
return diceImpl(rnd, proportions);
}
/// Ditto
size_t dice(R, Range)(ref R rnd, Range proportions)
if (isForwardRange!Range && isNumeric!(ElementType!Range) && !isArray!Range)
{
return diceImpl(rnd, proportions);
}
/// Ditto
size_t dice(Range)(Range proportions)
if (isForwardRange!Range && isNumeric!(ElementType!Range) && !isArray!Range)
{
return diceImpl(rndGen, proportions);
}
/// Ditto
size_t dice(Num)(Num[] proportions...)
if (isNumeric!Num)
{
return diceImpl(rndGen, proportions);
}
private size_t diceImpl(Rng, Range)(ref Rng rng, Range proportions)
if (isForwardRange!Range && isNumeric!(ElementType!Range) && isForwardRange!Rng)
{
double sum = reduce!("(assert(b >= 0), a + b)")(0.0, proportions.save);
enforce(sum > 0, "Proportions in a dice cannot sum to zero");
immutable point = uniform(0.0, sum, rng);
assert(point < sum);
auto mass = 0.0;
size_t i = 0;
foreach (e; proportions)
{
mass += e;
if (point < mass) return i;
i++;
}
// this point should not be reached
assert(false);
}
unittest
{
auto rnd = Random(unpredictableSeed);
auto i = dice(rnd, 0.0, 100.0);
assert(i == 1);
i = dice(rnd, 100.0, 0.0);
assert(i == 0);
i = dice(100U, 0U);
assert(i == 0);
}
/**
Covers a given range $(D r) in a random manner, i.e. goes through each
element of $(D r) once and only once, just in a random order. $(D r)
must be a random-access range with length.
If no random number generator is passed to $(D randomCover), the
thread-global RNG rndGen will be used internally.
Example:
----
int[] a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8 ];
foreach (e; randomCover(a))
{
writeln(e);
}
----
$(B WARNING:) If an alternative RNG is desired, it is essential for this
to be a $(I new) RNG seeded in an unpredictable manner. Passing it a RNG
used elsewhere in the program will result in unintended correlations,
due to the current implementation of RNGs as value types.
Example:
----
int[] a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8 ];
foreach (e; randomCover(a, Random(unpredictableSeed))) // correct!
{
writeln(e);
}
foreach (e; randomCover(a, rndGen)) // DANGEROUS!! rndGen gets copied by value
{
writeln(e);
}
foreach (e; randomCover(a, rndGen)) // ... so this second random cover
{ // will output the same sequence as
writeln(e); // the previous one.
}
----
These issues will be resolved in a second-generation std.random that
re-implements random number generators as reference types.
*/
struct RandomCover(Range, UniformRNG = void)
if (isRandomAccessRange!Range && (isUniformRNG!UniformRNG || is(UniformRNG == void)))
{
private Range _input;
private bool[] _chosen;
private size_t _current;
private size_t _alreadyChosen = 0;
static if (is(UniformRNG == void))
{
this(Range input)
{
_input = input;
_chosen.length = _input.length;
_alreadyChosen = 0;
}
}
else
{
private UniformRNG _rng;
this(Range input, ref UniformRNG rng)
{
_input = input;
_rng = rng;
_chosen.length = _input.length;
_alreadyChosen = 0;
}
this(Range input, UniformRNG rng)
{
this(input, rng);
}
}
static if (hasLength!Range)
{
@property size_t length()
{
if (_alreadyChosen == 0)
{
return _input.length;
}
else
{
return (1 + _input.length) - _alreadyChosen;
}
}
}
@property auto ref front()
{
if (_alreadyChosen == 0)
{
_chosen[] = false;
popFront();
}
return _input[_current];
}
void popFront()
{
if (_alreadyChosen >= _input.length)
{
// No more elements
++_alreadyChosen; // means we're done
return;
}
size_t k = _input.length - _alreadyChosen;
size_t i;
foreach (e; _input)
{
if (_chosen[i]) { ++i; continue; }
// Roll a dice with k faces
static if (is(UniformRNG == void))
{
auto chooseMe = uniform(0, k) == 0;
}
else
{
auto chooseMe = uniform(0, k, _rng) == 0;
}
assert(k > 1 || chooseMe);
if (chooseMe)
{
_chosen[i] = true;
_current = i;
++_alreadyChosen;
return;
}
--k;
++i;
}
}
static if (isForwardRange!UniformRNG)
{
@property typeof(this) save()
{
auto ret = this;
ret._input = _input.save;
ret._rng = _rng.save;
return ret;
}
}
@property bool empty() { return _alreadyChosen > _input.length; }
}
/// Ditto
auto randomCover(Range, UniformRNG)(Range r, auto ref UniformRNG rng)
if (isRandomAccessRange!Range && isUniformRNG!UniformRNG)
{
return RandomCover!(Range, UniformRNG)(r, rng);
}
/// Ditto
auto randomCover(Range)(Range r)
if (isRandomAccessRange!Range)
{
return RandomCover!(Range, void)(r);
}
unittest
{
int[] a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8 ];
foreach (UniformRNG; TypeTuple!(void, PseudoRngTypes))
{
static if (is(UniformRNG == void))
{
auto rc = randomCover(a);
static assert(isInputRange!(typeof(rc)));
static assert(!isForwardRange!(typeof(rc)));
}
else
{
auto rng = UniformRNG(unpredictableSeed);
auto rc = randomCover(a, rng);
static assert(isForwardRange!(typeof(rc)));
// check for constructor passed a value-type RNG
auto rc2 = RandomCover!(int[], UniformRNG)(a, UniformRNG(unpredictableSeed));
static assert(isForwardRange!(typeof(rc2)));
}
int[] b = new int[9];
uint i;
foreach (e; rc)
{
//writeln(e);
b[i++] = e;
}
sort(b);
assert(a == b, text(b));
}
}
// RandomSample
/**
Selects a random subsample out of $(D r), containing exactly $(D n)
elements. The order of elements is the same as in the original
range. The total length of $(D r) must be known. If $(D total) is
passed in, the total number of sample is considered to be $(D
total). Otherwise, $(D RandomSample) uses $(D r.length).
$(D RandomSample) implements Jeffrey Scott Vitter's Algorithm D
(see Vitter $(WEB dx.doi.org/10.1145/358105.893, 1984), $(WEB
dx.doi.org/10.1145/23002.23003, 1987)), which selects a sample
of size $(D n) in O(n) steps and requiring O(n) random variates,
regardless of the size of the data being sampled. The exception
to this is if traversing k elements on the input range is itself
an O(k) operation (e.g. when sampling lines from an input file),
in which case the sampling calculation will inevitably be of
O(total).
RandomSample will throw an exception if $(D total) is verifiably
less than the total number of elements available in the input,
or if $(D n > total).
If no random number generator is passed to $(D randomSample), the
thread-global RNG rndGen will be used internally.
Example:
----
int[] a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ];
// Print 5 random elements picked off from a
foreach (e; randomSample(a, 5))
{
writeln(e);
}
----
$(B WARNING:) If an alternative RNG is desired, it is essential for this
to be a $(I new) RNG seeded in an unpredictable manner. Passing it a RNG
used elsewhere in the program will result in unintended correlations,
due to the current implementation of RNGs as value types.
Example:
----
int[] a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ];
foreach (e; randomSample(a, 5, Random(unpredictableSeed))) // correct!
{
writeln(e);
}
foreach (e; randomSample(a, 5, rndGen)) // DANGEROUS!! rndGen gets
{ // copied by value
writeln(e);
}
foreach (e; randomSample(a, 5, rndGen)) // ... so this second random
{ // sample will select the same
writeln(e); // values as the previous one.
}
----
These issues will be resolved in a second-generation std.random that
re-implements random number generators as reference types.
*/
struct RandomSample(Range, UniformRNG = void)
if (isInputRange!Range && (isUniformRNG!UniformRNG || is(UniformRNG == void)))
{
private size_t _available, _toSelect;
private enum ushort _alphaInverse = 13; // Vitter's recommended value.
private double _Vprime;
private Range _input;
private size_t _index;
private enum Skip { None, A, D };
private Skip _skip = Skip.None;
// If we're using the default thread-local random number generator then
// we shouldn't store a copy of it here. UniformRNG == void is a sentinel
// for this. If we're using a user-specified generator then we have no
// choice but to store a copy.
static if (is(UniformRNG == void))
{
static if (hasLength!Range)
{
this(Range input, size_t howMany)
{
_input = input;
initialize(howMany, input.length);
}
}
this(Range input, size_t howMany, size_t total)
{
_input = input;
initialize(howMany, total);
}
}
else
{
UniformRNG _rng;
static if (hasLength!Range)
{
this(Range input, size_t howMany, ref UniformRNG rng)
{
_rng = rng;
_input = input;
initialize(howMany, input.length);
}
this(Range input, size_t howMany, UniformRNG rng)
{
this(input, howMany, rng);
}
}
this(Range input, size_t howMany, size_t total, ref UniformRNG rng)
{
_rng = rng;
_input = input;
initialize(howMany, total);
}
this(Range input, size_t howMany, size_t total, UniformRNG rng)
{
this(input, howMany, total, rng);
}
}
private void initialize(size_t howMany, size_t total)
{
_available = total;
_toSelect = howMany;
enforce(_toSelect <= _available,
text("RandomSample: cannot sample ", _toSelect,
" items when only ", _available, " are available"));
static if (hasLength!Range)
{
enforce(_available <= _input.length,
text("RandomSample: specified ", _available,
" items as available when input contains only ",
_input.length));
}
}
private void initializeFront()
{
assert(_skip == Skip.None);
// We can save ourselves a random variate by checking right
// at the beginning if we should use Algorithm A.
if ((_alphaInverse * _toSelect) > _available)
{
_skip = Skip.A;
}
else
{
_skip = Skip.D;
_Vprime = newVprime(_toSelect);
}
prime();
}
/**
Range primitives.
*/
@property bool empty() const
{
return _toSelect == 0;
}
@property auto ref front()
{
assert(!empty);
// The first sample point must be determined here to avoid
// having it always correspond to the first element of the
// input. The rest of the sample points are determined each
// time we call popFront().
if (_skip == Skip.None)
{
initializeFront();
}
return _input.front;
}
/// Ditto
void popFront()
{
// First we need to check if the sample has
// been initialized in the first place.
if (_skip == Skip.None)
{
initializeFront();
}
_input.popFront();
--_available;
--_toSelect;
++_index;
prime();
}
/// Ditto
static if (isForwardRange!Range && isForwardRange!UniformRNG)
{
@property typeof(this) save()
{
auto ret = this;
ret._input = _input.save;
ret._rng = _rng.save;
return ret;
}
}
/// Ditto
@property size_t length()
{
return _toSelect;
}
/**
Returns the index of the visited record.
*/
@property size_t index()
{
if (_skip == Skip.None)
{
initializeFront();
}
return _index;
}
private size_t skip()
{
assert(_skip != Skip.None);
// Step D1: if the number of points still to select is greater
// than a certain proportion of the remaining data points, i.e.
// if n >= alpha * N where alpha = 1/13, we carry out the
// sampling with Algorithm A.
if (_skip == Skip.A)
{
return skipA();
}
else if ((_alphaInverse * _toSelect) > _available)
{
// We shouldn't get here unless the current selected
// algorithm is D.
assert(_skip == Skip.D);
_skip = Skip.A;
return skipA();
}
else
{
assert(_skip == Skip.D);
return skipD();
}
}
/*
Vitter's Algorithm A, used when the ratio of needed sample values
to remaining data values is sufficiently large.
*/
private size_t skipA()
{
size_t s;
double v, quot, top;
if (_toSelect==1)
{
static if (is(UniformRNG == void))
{
s = uniform(0, _available);
}
else
{
s = uniform(0, _available, _rng);
}
}
else
{
v = 0;
top = _available - _toSelect;
quot = top / _available;
static if (is(UniformRNG == void))
{
v = uniform!"()"(0.0, 1.0);
}
else
{
v = uniform!"()"(0.0, 1.0, _rng);
}
while (quot > v)
{
++s;
quot *= (top - s) / (_available - s);
}
}
return s;
}
/*
Randomly reset the value of _Vprime.
*/
private double newVprime(size_t remaining)
{
static if (is(UniformRNG == void))
{
double r = uniform!"()"(0.0, 1.0);
}
else
{
double r = uniform!"()"(0.0, 1.0, _rng);
}
return r ^^ (1.0 / remaining);
}
/*
Vitter's Algorithm D. For an extensive description of the algorithm
and its rationale, see:
* Vitter, J.S. (1984), "Faster methods for random sampling",
Commun. ACM 27(7): 703--718
* Vitter, J.S. (1987) "An efficient algorithm for sequential random
sampling", ACM Trans. Math. Softw. 13(1): 58-67.
Variable names are chosen to match those in Vitter's paper.
*/
private size_t skipD()
{
// Confirm that the check in Step D1 is valid and we
// haven't been sent here by mistake
assert((_alphaInverse * _toSelect) <= _available);
// Now it's safe to use the standard Algorithm D mechanism.
if (_toSelect > 1)
{
size_t s;
size_t qu1 = 1 + _available - _toSelect;
double x, y1;
assert(!_Vprime.isNaN);
while (true)
{
// Step D2: set values of x and u.
for (x = _available * (1-_Vprime), s = cast(size_t) trunc(x);
s >= qu1;
x = _available * (1-_Vprime), s = cast(size_t) trunc(x))
{
_Vprime = newVprime(_toSelect);
}
static if (is(UniformRNG == void))
{
double u = uniform!"()"(0.0, 1.0);
}
else
{
double u = uniform!"()"(0.0, 1.0, _rng);
}
y1 = (u * (cast(double) _available) / qu1) ^^ (1.0/(_toSelect - 1));
_Vprime = y1 * ((-x/_available)+1.0) * ( qu1/( (cast(double) qu1) - s ) );
// Step D3: if _Vprime <= 1.0 our work is done and we return S.
// Otherwise ...
if (_Vprime > 1.0)
{
size_t top = _available - 1, limit;
double y2 = 1.0, bottom;
if (_toSelect > (s+1))
{
bottom = _available - _toSelect;
limit = _available - s;
}
else
{
bottom = _available - (s+1);
limit = qu1;
}
foreach (size_t t; limit .. _available)
{
y2 *= top/bottom;
top--;
bottom--;
}
// Step D4: decide whether or not to accept the current value of S.
if (_available/(_available-x) < y1 * (y2 ^^ (1.0/(_toSelect-1))))
{
// If it's not acceptable, we generate a new value of _Vprime
// and go back to the start of the for (;;) loop.
_Vprime = newVprime(_toSelect);
}
else
{
// If it's acceptable we generate a new value of _Vprime
// based on the remaining number of sample points needed,
// and return S.
_Vprime = newVprime(_toSelect-1);
return s;
}
}
else
{
// Return if condition D3 satisfied.
return s;
}
}
}
else
{
// If only one sample point remains to be taken ...
return cast(size_t) trunc(_available * _Vprime);
}
}
private void prime()
{
if (empty)
{
return;
}
assert(_available && _available >= _toSelect);
immutable size_t s = skip();
assert(s + _toSelect <= _available);
static if (hasLength!Range)
{
assert(s + _toSelect <= _input.length);
}
assert(!_input.empty);
_input.popFrontExactly(s);
_index += s;
_available -= s;
assert(_available > 0);
}
}
/// Ditto
auto randomSample(Range)(Range r, size_t n, size_t total)
if (isInputRange!Range)
{
return RandomSample!(Range, void)(r, n, total);
}
/// Ditto
auto randomSample(Range)(Range r, size_t n)
if (isInputRange!Range && hasLength!Range)
{
return RandomSample!(Range, void)(r, n, r.length);
}
/// Ditto
auto randomSample(Range, UniformRNG)(Range r, size_t n, size_t total, auto ref UniformRNG rng)
if (isInputRange!Range && isUniformRNG!UniformRNG)
{
return RandomSample!(Range, UniformRNG)(r, n, total, rng);
}
/// Ditto
auto randomSample(Range, UniformRNG)(Range r, size_t n, auto ref UniformRNG rng)
if (isInputRange!Range && hasLength!Range && isUniformRNG!UniformRNG)
{
return RandomSample!(Range, UniformRNG)(r, n, r.length, rng);
}
unittest
{
// For test purposes, an infinite input range
struct TestInputRange
{
private auto r = recurrence!"a[n-1] + 1"(0);
bool empty() @property const pure nothrow { return r.empty; }
auto front() @property pure nothrow { return r.front; }
void popFront() pure nothrow { r.popFront(); }
}
static assert(isInputRange!TestInputRange);
static assert(!isForwardRange!TestInputRange);
int[] a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ];
foreach (UniformRNG; PseudoRngTypes)
{
auto rng = UniformRNG(unpredictableSeed);
/* First test the most general case: randomSample of input range, with and
* without a specified random number generator.
*/
static assert(isInputRange!(typeof(randomSample(TestInputRange(), 5, 10))));
static assert(isInputRange!(typeof(randomSample(TestInputRange(), 5, 10, rng))));
static assert(!isForwardRange!(typeof(randomSample(TestInputRange(), 5, 10))));
static assert(!isForwardRange!(typeof(randomSample(TestInputRange(), 5, 10, rng))));
// test case with range initialized by direct call to struct
{
auto sample =
RandomSample!(TestInputRange, UniformRNG)
(TestInputRange(), 5, 10, UniformRNG(unpredictableSeed));
static assert(isInputRange!(typeof(sample)));
static assert(!isForwardRange!(typeof(sample)));
}
/* Now test the case of an input range with length. We ignore the cases
* already covered by the previous tests.
*/
static assert(isInputRange!(typeof(randomSample(TestInputRange().takeExactly(10), 5))));
static assert(isInputRange!(typeof(randomSample(TestInputRange().takeExactly(10), 5, rng))));
static assert(!isForwardRange!(typeof(randomSample(TestInputRange().takeExactly(10), 5))));
static assert(!isForwardRange!(typeof(randomSample(TestInputRange().takeExactly(10), 5, rng))));
// test case with range initialized by direct call to struct
{
auto sample =
RandomSample!(typeof(TestInputRange().takeExactly(10)), UniformRNG)
(TestInputRange().takeExactly(10), 5, 10, UniformRNG(unpredictableSeed));
static assert(isInputRange!(typeof(sample)));
static assert(!isForwardRange!(typeof(sample)));
}
// Now test the case of providing a forward range as input.
static assert(!isForwardRange!(typeof(randomSample(a, 5))));
static if (isForwardRange!UniformRNG)
{
static assert(isForwardRange!(typeof(randomSample(a, 5, rng))));
// ... and test with range initialized directly
{
auto sample =
RandomSample!(int[], UniformRNG)
(a, 5, UniformRNG(unpredictableSeed));
static assert(isForwardRange!(typeof(sample)));
}
}
else
{
static assert(isInputRange!(typeof(randomSample(a, 5, rng))));
static assert(!isForwardRange!(typeof(randomSample(a, 5, rng))));
// ... and test with range initialized directly
{
auto sample =
RandomSample!(int[], UniformRNG)
(a, 5, UniformRNG(unpredictableSeed));
static assert(isInputRange!(typeof(sample)));
static assert(!isForwardRange!(typeof(sample)));
}
}
/* Check that randomSample will throw an error if we claim more
* items are available than there actually are, or if we try to
* sample more items than are available. */
assert(collectExceptionMsg(randomSample(a, 5, 15)) == "RandomSample: specified 15 items as available when input contains only 10");
assert(collectExceptionMsg(randomSample(a, 15)) == "RandomSample: cannot sample 15 items when only 10 are available");
assert(collectExceptionMsg(randomSample(a, 9, 8)) == "RandomSample: cannot sample 9 items when only 8 are available");
assert(collectExceptionMsg(randomSample(TestInputRange(), 12, 11)) == "RandomSample: cannot sample 12 items when only 11 are available");
/* Check that sampling algorithm never accidentally overruns the end of
* the input range. If input is an InputRange without .length, this
* relies on the user specifying the total number of available items
* correctly.
*/
{
uint i = 0;
foreach (e; randomSample(a, a.length))
{
assert(e == i);
++i;
}
assert(i == a.length);
i = 0;
foreach (e; randomSample(TestInputRange(), 17, 17))
{
assert(e == i);
++i;
}
assert(i == 17);
}
// Check length properties of random samples.
assert(randomSample(a, 5).length == 5);
assert(randomSample(a, 5, 10).length == 5);
assert(randomSample(a, 5, rng).length == 5);
assert(randomSample(a, 5, 10, rng).length == 5);
assert(randomSample(TestInputRange(), 5, 10).length == 5);
assert(randomSample(TestInputRange(), 5, 10, rng).length == 5);
// ... and emptiness!
assert(randomSample(a, 0).empty);
assert(randomSample(a, 0, 5).empty);
assert(randomSample(a, 0, rng).empty);
assert(randomSample(a, 0, 5, rng).empty);
assert(randomSample(TestInputRange(), 0, 10).empty);
assert(randomSample(TestInputRange(), 0, 10, rng).empty);
/* Test that the (lazy) evaluation of random samples works correctly.
*
* We cover 2 different cases: a sample where the ratio of sample points
* to total points is greater than the threshold for using Algorithm, and
* one where the ratio is small enough (< 1/13) for Algorithm D to be used.
*
* For each, we also cover the case with and without a specified RNG.
*/
{
// Small sample/source ratio, no specified RNG.
uint i = 0;
foreach (e; randomSample(randomCover(a), 5))
{
++i;
}
assert(i == 5);
// Small sample/source ratio, specified RNG.
i = 0;
foreach (e; randomSample(randomCover(a), 5, rng))
{
++i;
}
assert(i == 5);
// Large sample/source ratio, no specified RNG.
i = 0;
foreach (e; randomSample(TestInputRange(), 123, 123_456))
{
++i;
}
assert(i == 123);
// Large sample/source ratio, specified RNG.
i = 0;
foreach (e; randomSample(TestInputRange(), 123, 123_456, rng))
{
++i;
}
assert(i == 123);
/* Sample/source ratio large enough to start with Algorithm D,
* small enough to switch to Algorithm A.
*/
i = 0;
foreach (e; randomSample(TestInputRange(), 10, 131))
{
++i;
}
assert(i == 10);
}
// Test that the .index property works correctly
{
auto sample1 = randomSample(TestInputRange(), 654, 654_321);
for (; !sample1.empty; sample1.popFront())
{
assert(sample1.front == sample1.index);
}
auto sample2 = randomSample(TestInputRange(), 654, 654_321, rng);
for (; !sample2.empty; sample2.popFront())
{
assert(sample2.front == sample2.index);
}
/* Check that it also works if .index is called before .front.
* See: http://d.puremagic.com/issues/show_bug.cgi?id=10322
*/
auto sample3 = randomSample(TestInputRange(), 654, 654_321);
for (; !sample3.empty; sample3.popFront())
{
assert(sample3.index == sample3.front);
}
auto sample4 = randomSample(TestInputRange(), 654, 654_321, rng);
for (; !sample4.empty; sample4.popFront())
{
assert(sample4.index == sample4.front);
}
}
/* Test behaviour if .popFront() is called before sample is read.
* This is a rough-and-ready check that the statistical properties
* are in the ballpark -- not a proper validation of statistical
* quality! This incidentally also checks for reference-type
* initialization bugs, as the foreach() loop will operate on a
* copy of the popFronted (and hence initialized) sample.
*/
{
size_t count0, count1, count99;
foreach(_; 0 .. 100_000)
{
auto sample = randomSample(iota(100), 5);
sample.popFront();
foreach(s; sample)
{
if (s == 0)
{
++count0;
}
else if (s == 1)
{
++count1;
}
else if (s == 99)
{
++count99;
}
}
}
/* Statistical assumptions here: this is a sequential sampling process
* so (i) 0 can only be the first sample point, so _can't_ be in the
* remainder of the sample after .popFront() is called. (ii) By similar
* token, 1 can only be in the remainder if it's the 2nd point of the
* whole sample, and hence if 0 was the first; probability of 0 being
* first and 1 second is 5/100 * 4/99 (thank you, Algorithm S:-) and
* so the mean count of 1 should be about 202. Finally, 99 can only
* be the _last_ sample point to be picked, so its probability of
* inclusion should be independent of the .popFront() and it should
* occur with frequency 5/100, hence its count should be about 5000.
* Unfortunately we have to set quite a high tolerance because with
* sample size small enough for unittests to run in reasonable time,
* the variance can be quite high.
*/
assert(count0 == 0);
assert(count1 < 300, text("1: ", count1, " > 300."));
assert(4_700 < count99, text("99: ", count99, " < 4700."));
assert(count99 < 5_300, text("99: ", count99, " > 5300."));
}
/* Odd corner-cases: RandomSample has 2 constructors that are not called
* by the randomSample() helper functions, but that can be used if the
* constructor is called directly. These cover the case of the user
* specifying input but not input length.
*/
{
auto input1 = TestInputRange().takeExactly(456_789);
static assert(hasLength!(typeof(input1)));
auto sample1 = RandomSample!(typeof(input1), void)(input1, 789);
static assert(isInputRange!(typeof(sample1)));
static assert(!isForwardRange!(typeof(sample1)));
assert(sample1.length == 789);
assert(sample1._available == 456_789);
uint i = 0;
for (; !sample1.empty; sample1.popFront())
{
assert(sample1.front == sample1.index);
++i;
}
assert(i == 789);
auto input2 = TestInputRange().takeExactly(456_789);
static assert(hasLength!(typeof(input2)));
auto sample2 = RandomSample!(typeof(input2), typeof(rng))(input2, 789, rng);
static assert(isInputRange!(typeof(sample2)));
static assert(!isForwardRange!(typeof(sample2)));
assert(sample2.length == 789);
assert(sample2._available == 456_789);
i = 0;
for (; !sample2.empty; sample2.popFront())
{
assert(sample2.front == sample2.index);
++i;
}
assert(i == 789);
}
/* Test that the save property works where input is a forward range,
* and RandomSample is using a (forward range) random number generator
* that is not rndGen.
*/
static if (isForwardRange!UniformRNG)
{
auto sample1 = randomSample(a, 5, rng);
auto sample2 = sample1.save;
assert(sample1.array() == sample2.array());
}
// Bugzilla 8314
{
auto sample(RandomGen)(uint seed) { return randomSample(a, 1, RandomGen(seed)).front; }
// Start from 1 because not all RNGs accept 0 as seed.
immutable fst = sample!UniformRNG(1);
uint n = 1;
while (sample!UniformRNG(++n) == fst && n < n.max) {}
assert(n < n.max);
}
}
}
|