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
|
/*
* Copyright (c) 2002-2006 Samit Basu
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include "Exception.hpp"
#include <cstdlib>
#include <cstdio>
#include <math.h>
#include "RanLib.hpp"
/*
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.keio.ac.jp/matumoto/emt.html
email: matumoto@math.keio.ac.jp
*/
/* Period parameters */
#define N 624
#define M 397
#define MATRIX_A 0x9908b0dfUL /* constant vector a */
#define UPPER_MASK 0x80000000UL /* most significant w-r bits */
#define LOWER_MASK 0x7fffffffUL /* least significant r bits */
static unsigned long mt[N]; /* the array for the state vector */
static int mti=N+1; /* mti==N+1 means mt[N] is not initialized */
void GetRandStateVect(unsigned int* dt) {
for (int i=0;i<N;i++)
dt[i] = mt[i];
dt[N] = mti;
}
void SetRandStateVect(unsigned int* dt) {
for (int i=0;i<N;i++)
mt[i] = dt[i];
mti = dt[N];
}
/* initializes mt[N] with a seed */
void init_genrand(unsigned long s)
{
mt[0]= s & 0xffffffffUL;
for (mti=1; mti<N; mti++) {
mt[mti] =
(1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + 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] &= 0xffffffffUL;
/* for >32 bit machines */
}
}
/* initialize by an array with array-length */
/* init_key is the array for initializing keys */
/* key_length is its length */
void init_by_array(unsigned long init_key[], unsigned long key_length)
{
int i, j, k;
init_genrand(19650218UL);
i=1; j=0;
k = (N>key_length ? N : key_length);
for (; k; k--) {
mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL))
+ init_key[j] + j; /* non linear */
mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
i++; j++;
if (i>=N) { mt[0] = mt[N-1]; i=1; }
if (j>=(int) key_length) j=0;
}
for (k=N-1; k; k--) {
mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL))
- i; /* non linear */
mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
i++;
if (i>=N) { mt[0] = mt[N-1]; i=1; }
}
mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */
}
/* generates a random number on [0,0xffffffff]-interval */
unsigned long genrand_int32(void)
{
unsigned long y;
static unsigned long mag01[2]={0x0UL, MATRIX_A};
/* mag01[x] = x * MATRIX_A for x=0,1 */
if (mti >= N) { /* generate N words at one time */
int kk;
if (mti == N+1) /* if init_genrand() has not been called, */
init_genrand(5489UL); /* a default initial seed is used */
for (kk=0;kk<N-M;kk++) {
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1UL];
}
for (;kk<N-1;kk++) {
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1UL];
}
y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL];
mti = 0;
}
y = mt[mti++];
/* Tempering */
y ^= (y >> 11);
y ^= (y << 7) & 0x9d2c5680UL;
y ^= (y << 15) & 0xefc60000UL;
y ^= (y >> 18);
return y;
}
/* generates a random number on [0,0x7fffffff]-interval */
long genrand_int31(void)
{
return (long)(genrand_int32()>>1);
}
/* generates a random number on [0,1]-real-interval */
double genrand_real1(void)
{
return genrand_int32()*(1.0/4294967295.0);
/* divided by 2^32-1 */
}
/* Generates a random number on [0,1)-real-interval */
double genrand_real2(void)
{
return genrand_int32()*(1.0/4294967296.0);
/* divided by 2^32 */
}
/* generates a random number on (0,1)-real-interval */
double genrand_real3(void)
{
return (((double)genrand_int32()) + 0.5)*(1.0/4294967296.0);
/* divided by 2^32 */
}
/* generates a random number on [0,1) with 53-bit resolution*/
double genrand_res53(void)
{
unsigned long a=genrand_int32()>>5, b=genrand_int32()>>6;
return(a*67108864.0+b)*(1.0/9007199254740992.0);
}
/* These real versions are due to Isaku Wada, 2002/01/09 added */
void advnst(long k)
/*
**********************************************************************
void advnst(long k)
ADV-a-N-ce ST-ate
Advances the state of the current generator by 2^K values and
resets the initial seed to that value.
This is a transcription from Pascal to Fortran of routine
Advance_State from the paper
L'Ecuyer, P. and Cote, S. "Implementing a Random Number Package
with Splitting Facilities." ACM Transactions on Mathematical
Software, 17:98-111 (1991)
Arguments
k -> The generator is advanced by2^K values
**********************************************************************
*/
{
#define numg 32L
extern void gsrgs(long getset,long *qvalue);
extern void gscgn(long getset,long *g);
extern long Xm1,Xm2,Xa1,Xa2,Xcg1[],Xcg2[];
static long g,i,ib1,ib2;
static long qrgnin;
/*
Abort unless random number generator initialized
*/
gsrgs(0L,&qrgnin);
if(qrgnin) goto S10;
throw Exception("RANLIB Error: ADVNST called before random generator initialized - ABORT");
S10:
gscgn(0L,&g);
ib1 = Xa1;
ib2 = Xa2;
for(i=1; i<=k; i++) {
ib1 = mltmod(ib1,ib1,Xm1);
ib2 = mltmod(ib2,ib2,Xm2);
}
setsd(mltmod(ib1,*(Xcg1+g-1),Xm1),mltmod(ib2,*(Xcg2+g-1),Xm2));
/*
NOW, IB1 = A1**K AND IB2 = A2**K
*/
#undef numg
}
void getsd(long *iseed1,long *iseed2)
/*
**********************************************************************
void getsd(long *iseed1,long *iseed2)
GET SeeD
Returns the value of two integer seeds of the current generator
This is a transcription from Pascal to Fortran of routine
Get_State from the paper
L'Ecuyer, P. and Cote, S. "Implementing a Random Number Package
with Splitting Facilities." ACM Transactions on Mathematical
Software, 17:98-111 (1991)
Arguments
iseed1 <- First integer seed of generator G
iseed2 <- Second integer seed of generator G
**********************************************************************
*/
{
#define numg 32L
extern void gsrgs(long getset,long *qvalue);
extern void gscgn(long getset,long *g);
extern long Xcg1[],Xcg2[];
static long g;
static long qrgnin;
/*
Abort unless random number generator initialized
*/
gsrgs(0L,&qrgnin);
if(qrgnin) goto S10;
fprintf(stderr,"%s\n",
" GETSD called before random number generator initialized -- abort!");
exit(0);
S10:
gscgn(0L,&g);
*iseed1 = *(Xcg1+g-1);
*iseed2 = *(Xcg2+g-1);
#undef numg
}
long ignlgi(void)
/*
**********************************************************************
long ignlgi(void)
GeNerate LarGe Integer
Returns a random integer following a uniform distribution over
(1, 2147483562) using the current generator.
This is a transcription from Pascal to Fortran of routine
Random from the paper
L'Ecuyer, P. and Cote, S. "Implementing a Random Number Package
with Splitting Facilities." ACM Transactions on Mathematical
Software, 17:98-111 (1991)
**********************************************************************
*/
{
#define numg 32L
extern void gsrgs(long getset,long *qvalue);
extern void gssst(long getset,long *qset);
extern void gscgn(long getset,long *g);
extern void inrgcm(void);
extern long Xm1,Xm2,Xa1,Xa2,Xcg1[],Xcg2[];
extern long Xqanti[];
static long ignlgi,curntg,k,s1,s2,z;
static long qqssd,qrgnin;
/*
IF THE RANDOM NUMBER PACKAGE HAS NOT BEEN INITIALIZED YET, DO SO.
IT CAN BE INITIALIZED IN ONE OF TWO WAYS : 1) THE FIRST CALL TO
THIS ROUTINE 2) A CALL TO SETALL.
*/
gsrgs(0L,&qrgnin);
if(!qrgnin) inrgcm();
gssst(0,&qqssd);
if(!qqssd) setall(1234567890L,123456789L);
/*
Get Current Generator
*/
gscgn(0L,&curntg);
s1 = *(Xcg1+curntg-1);
s2 = *(Xcg2+curntg-1);
k = s1/53668L;
s1 = Xa1*(s1-k*53668L)-k*12211;
if(s1 < 0) s1 += Xm1;
k = s2/52774L;
s2 = Xa2*(s2-k*52774L)-k*3791;
if(s2 < 0) s2 += Xm2;
*(Xcg1+curntg-1) = s1;
*(Xcg2+curntg-1) = s2;
z = s1-s2;
if(z < 1) z += (Xm1-1);
if(*(Xqanti+curntg-1)) z = Xm1-z;
ignlgi = z;
return ignlgi;
#undef numg
}
void initgn(long isdtyp)
/*
**********************************************************************
void initgn(long isdtyp)
INIT-ialize current G-e-N-erator
Reinitializes the state of the current generator
This is a transcription from Pascal to Fortran of routine
Init_Generator from the paper
L'Ecuyer, P. and Cote, S. "Implementing a Random Number Package
with Splitting Facilities." ACM Transactions on Mathematical
Software, 17:98-111 (1991)
Arguments
isdtyp -> The state to which the generator is to be set
isdtyp = -1 => sets the seeds to their initial value
isdtyp = 0 => sets the seeds to the first value of
the current block
isdtyp = 1 => sets the seeds to the first value of
the next block
**********************************************************************
*/
{
#define numg 32L
extern void gsrgs(long getset,long *qvalue);
extern void gscgn(long getset,long *g);
extern long Xm1,Xm2,Xa1w,Xa2w,Xig1[],Xig2[],Xlg1[],Xlg2[],Xcg1[],Xcg2[];
static long g;
static long qrgnin;
/*
Abort unless random number generator initialized
*/
gsrgs(0L,&qrgnin);
if(qrgnin) goto S10;
fprintf(stderr,"%s\n",
" INITGN called before random number generator initialized -- abort!");
exit(1);
S10:
gscgn(0L,&g);
if(-1 != isdtyp) goto S20;
*(Xlg1+g-1) = *(Xig1+g-1);
*(Xlg2+g-1) = *(Xig2+g-1);
goto S50;
S20:
if(0 != isdtyp) goto S30;
goto S50;
S30:
/*
do nothing
*/
if(1 != isdtyp) goto S40;
*(Xlg1+g-1) = mltmod(Xa1w,*(Xlg1+g-1),Xm1);
*(Xlg2+g-1) = mltmod(Xa2w,*(Xlg2+g-1),Xm2);
goto S50;
S40:
fprintf(stderr,"%s\n","isdtyp not in range in INITGN");
exit(1);
S50:
*(Xcg1+g-1) = *(Xlg1+g-1);
*(Xcg2+g-1) = *(Xlg2+g-1);
#undef numg
}
void inrgcm(void)
/*
**********************************************************************
void inrgcm(void)
INitialize Random number Generator CoMmon
Function
Initializes common area for random number generator. This saves
the nuisance of a BLOCK DATA routine and the difficulty of
assuring that the routine is loaded with the other routines.
**********************************************************************
*/
{
#define numg 32L
extern void gsrgs(long getset,long *qvalue);
extern long Xm1,Xm2,Xa1,Xa2,Xa1w,Xa2w,Xa1vw,Xa2vw;
extern long Xqanti[];
static long T1;
static long i;
/*
V=20; W=30;
A1W = MOD(A1**(2**W),M1) A2W = MOD(A2**(2**W),M2)
A1VW = MOD(A1**(2**(V+W)),M1) A2VW = MOD(A2**(2**(V+W)),M2)
If V or W is changed A1W, A2W, A1VW, and A2VW need to be recomputed.
An efficient way to precompute a**(2*j) MOD m is to start with
a and square it j times modulo m using the function MLTMOD.
*/
Xm1 = 2147483563L;
Xm2 = 2147483399L;
Xa1 = 40014L;
Xa2 = 40692L;
Xa1w = 1033780774L;
Xa2w = 1494757890L;
Xa1vw = 2082007225L;
Xa2vw = 784306273L;
for(i=0; i<numg; i++) *(Xqanti+i) = 0;
T1 = 1;
/*
Tell the world that common has been initialized
*/
gsrgs(1L,&T1);
#undef numg
}
void setall(long iseed1,long iseed2)
/*
**********************************************************************
void setall(long iseed1,long iseed2)
SET ALL random number generators
Sets the initial seed of generator 1 to ISEED1 and ISEED2. The
initial seeds of the other generators are set accordingly, and
all generators states are set to these seeds.
This is a transcription from Pascal to Fortran of routine
Set_Initial_Seed from the paper
L'Ecuyer, P. and Cote, S. "Implementing a Random Number Package
with Splitting Facilities." ACM Transactions on Mathematical
Software, 17:98-111 (1991)
Arguments
iseed1 -> First of two integer seeds
iseed2 -> Second of two integer seeds
**********************************************************************
*/
{
#define numg 32L
extern void gsrgs(long getset,long *qvalue);
extern void gssst(long getset,long *qset);
extern void gscgn(long getset,long *g);
extern long Xm1,Xm2,Xa1vw,Xa2vw,Xig1[],Xig2[];
static long T1;
static long g,ocgn;
static long qrgnin;
T1 = 1;
/*
TELL IGNLGI, THE ACTUAL NUMBER GENERATOR, THAT THIS ROUTINE
HAS BEEN CALLED.
*/
gssst(1,&T1);
gscgn(0L,&ocgn);
/*
Initialize Common Block if Necessary
*/
gsrgs(0L,&qrgnin);
if(!qrgnin) inrgcm();
*Xig1 = iseed1;
*Xig2 = iseed2;
initgn(-1L);
for(g=2; g<=numg; g++) {
*(Xig1+g-1) = mltmod(Xa1vw,*(Xig1+g-2),Xm1);
*(Xig2+g-1) = mltmod(Xa2vw,*(Xig2+g-2),Xm2);
gscgn(1L,&g);
initgn(-1L);
}
gscgn(1L,&ocgn);
#undef numg
}
void setant(long qvalue)
/*
**********************************************************************
void setant(long qvalue)
SET ANTithetic
Sets whether the current generator produces antithetic values. If
X is the value normally returned from a uniform [0,1] random
number generator then 1 - X is the antithetic value. If X is the
value normally returned from a uniform [0,N] random number
generator then N - 1 - X is the antithetic value.
All generators are initialized to NOT generate antithetic values.
This is a transcription from Pascal to Fortran of routine
Set_Antithetic from the paper
L'Ecuyer, P. and Cote, S. "Implementing a Random Number Package
with Splitting Facilities." ACM Transactions on Mathematical
Software, 17:98-111 (1991)
Arguments
qvalue -> nonzero if generator G is to generating antithetic
values, otherwise zero
**********************************************************************
*/
{
#define numg 32L
extern void gsrgs(long getset,long *qvalue);
extern void gscgn(long getset,long *g);
extern long Xqanti[];
static long g;
static long qrgnin;
/*
Abort unless random number generator initialized
*/
gsrgs(0L,&qrgnin);
if(qrgnin) goto S10;
fprintf(stderr,"%s\n",
" SETANT called before random number generator initialized -- abort!");
exit(1);
S10:
gscgn(0L,&g);
Xqanti[g-1] = qvalue;
#undef numg
}
void setsd(long iseed1,long iseed2)
/*
**********************************************************************
void setsd(long iseed1,long iseed2)
SET S-ee-D of current generator
Resets the initial seed of the current generator to ISEED1 and
ISEED2. The seeds of the other generators remain unchanged.
This is a transcription from Pascal to Fortran of routine
Set_Seed from the paper
L'Ecuyer, P. and Cote, S. "Implementing a Random Number Package
with Splitting Facilities." ACM Transactions on Mathematical
Software, 17:98-111 (1991)
Arguments
iseed1 -> First integer seed
iseed2 -> Second integer seed
**********************************************************************
*/
{
#define numg 32L
extern void gsrgs(long getset,long *qvalue);
extern void gscgn(long getset,long *g);
extern long Xig1[],Xig2[];
static long g;
static long qrgnin;
/*
Abort unless random number generator initialized
*/
gsrgs(0L,&qrgnin);
if(qrgnin) goto S10;
fprintf(stderr,"%s\n",
" SETSD called before random number generator initialized -- abort!");
exit(1);
S10:
gscgn(0L,&g);
*(Xig1+g-1) = iseed1;
*(Xig2+g-1) = iseed2;
initgn(-1L);
#undef numg
}
long Xm1,Xm2,Xa1,Xa2,Xcg1[32],Xcg2[32],Xa1w,Xa2w,Xig1[32],Xig2[32],Xlg1[32],
Xlg2[32],Xa1vw,Xa2vw;
long Xqanti[32];
#define ABS(x) ((x) >= 0 ? (x) : -(x))
#define min(a,b) ((a) <= (b) ? (a) : (b))
#define max(a,b) ((a) >= (b) ? (a) : (b))
void ftnstop(const char*);
float genbet(float aa,float bb)
/*
**********************************************************************
float genbet(float aa,float bb)
GeNerate BETa random deviate
Function
Returns a single random deviate from the beta distribution with
parameters A and B. The density of the beta is
x^(a-1) * (1-x)^(b-1) / B(a,b) for 0 < x < 1
Arguments
aa --> First parameter of the beta distribution
bb --> Second parameter of the beta distribution
Method
R. C. H. Cheng
Generating Beta Variatew with Nonintegral Shape Parameters
Communications of the ACM, 21:317-322 (1978)
(Algorithms BB and BC)
**********************************************************************
*/
{
#define expmax 89.0
#define infnty 1.0E38
static float olda = -1.0;
static float oldb = -1.0;
static float genbet,a,alpha,b,beta,delta,gamma,k1,k2,r,s,t,u1,u2,v,w,y,z;
static long qsame;
qsame = olda == aa && oldb == bb;
if(qsame) goto S20;
if(!(aa <= 0.0 || bb <= 0.0)) goto S10;
throw Exception("RANLIB Error: AA or BB <= 0 in GENBET - Abort!");
S10:
olda = aa;
oldb = bb;
S20:
if(!(min(aa,bb) > 1.0)) goto S100;
/*
Alborithm BB
Initialize
*/
if(qsame) goto S30;
a = min(aa,bb);
b = max(aa,bb);
alpha = a+b;
beta = sqrt((alpha-2.0)/(2.0*a*b-alpha));
gamma = a+1.0/beta;
S30:
S40:
u1 = ranf();
/*
Step 1
*/
u2 = ranf();
v = beta*log(u1/(1.0-u1));
if(!(v > expmax)) goto S50;
w = infnty;
goto S60;
S50:
w = a*exp(v);
S60:
z = pow(u1,2.0f)*u2;
r = gamma*v-1.3862944;
s = a+r-w;
/*
Step 2
*/
if(s+2.609438 >= 5.0*z) goto S70;
/*
Step 3
*/
t = log(z);
if(s > t) goto S70;
/*
Step 4
*/
if(r+alpha*log(alpha/(b+w)) < t) goto S40;
S70:
/*
Step 5
*/
if(!(aa == a)) goto S80;
genbet = w/(b+w);
goto S90;
S80:
genbet = b/(b+w);
S90:
goto S230;
S100:
/*
Algorithm BC
Initialize
*/
if(qsame) goto S110;
a = max(aa,bb);
b = min(aa,bb);
alpha = a+b;
beta = 1.0/b;
delta = 1.0+a-b;
k1 = delta*(1.38889E-2+4.16667E-2*b)/(a*beta-0.777778);
k2 = 0.25+(0.5+0.25/delta)*b;
S110:
S120:
u1 = ranf();
/*
Step 1
*/
u2 = ranf();
if(u1 >= 0.5) goto S130;
/*
Step 2
*/
y = u1*u2;
z = u1*y;
if(0.25*u2+z-y >= k1) goto S120;
goto S170;
S130:
/*
Step 3
*/
z = pow(u1,2.0f)*u2;
if(!(z <= 0.25)) goto S160;
v = beta*log(u1/(1.0-u1));
if(!(v > expmax)) goto S140;
w = infnty;
goto S150;
S140:
w = a*exp(v);
S150:
goto S200;
S160:
if(z >= k2) goto S120;
S170:
/*
Step 4
Step 5
*/
v = beta*log(u1/(1.0-u1));
if(!(v > expmax)) goto S180;
w = infnty;
goto S190;
S180:
w = a*exp(v);
S190:
if(alpha*(log(alpha/(b+w))+v)-1.3862944 < log(z)) goto S120;
S200:
/*
Step 6
*/
if(!(a == aa)) goto S210;
genbet = w/(b+w);
goto S220;
S210:
genbet = b/(b+w);
S230:
S220:
return genbet;
#undef expmax
#undef infnty
}
float genchi(float df)
/*
**********************************************************************
float genchi(float df)
Generate random value of CHIsquare variable
Function
Generates random deviate from the distribution of a chisquare
with DF degrees of freedom random variable.
Arguments
df --> Degrees of freedom of the chisquare
(Must be positive)
Method
Uses relation between chisquare and gamma.
**********************************************************************
*/
{
static float genchi;
if(!(df <= 0.0)) goto S10;
throw Exception("RANLIB Error:DF <= 0 in GENCHI - ABORT");
S10:
genchi = 2.0*gengam(1.0,df/2.0);
return genchi;
}
float genexp(float av)
/*
**********************************************************************
float genexp(float av)
GENerate EXPonential random deviate
Function
Generates a single random deviate from an exponential
distribution with mean AV.
Arguments
av --> The mean of the exponential distribution from which
a random deviate is to be generated.
Method
Renames SEXPO from TOMS as slightly modified by BWB to use RANF
instead of SUNIF.
For details see:
Ahrens, J.H. and Dieter, U.
Computer Methods for Sampling From the
Exponential and Normal Distributions.
Comm. ACM, 15,10 (Oct. 1972), 873 - 882.
**********************************************************************
*/
{
static float genexp;
genexp = sexpo()*av;
return genexp;
}
float genf(float dfn,float dfd)
/*
**********************************************************************
float genf(float dfn,float dfd)
GENerate random deviate from the F distribution
Function
Generates a random deviate from the F (variance ratio)
distribution with DFN degrees of freedom in the numerator
and DFD degrees of freedom in the denominator.
Arguments
dfn --> Numerator degrees of freedom
(Must be positive)
dfd --> Denominator degrees of freedom
(Must be positive)
Method
Directly generates ratio of chisquare variates
**********************************************************************
*/
{
static float genf,xden,xnum;
if(!(dfn <= 0.0 || dfd <= 0.0)) goto S10;
throw Exception("RANLIB Error:Degrees of freedom nonpositive in GENF - abort!");
S10:
xnum = genchi(dfn)/dfn;
/*
GENF = ( GENCHI( DFN ) / DFN ) / ( GENCHI( DFD ) / DFD )
*/
xden = genchi(dfd)/dfd;
if(!(xden <= 9.999999999998E-39*xnum)) goto S20;
throw Exception("RANLIB Error: GENF - generated numbers would cause overflow");
genf = 1.0E38;
goto S30;
S20:
genf = xnum/xden;
S30:
return genf;
}
float gengam(float a,float r)
/*
**********************************************************************
float gengam(float a,float r)
GENerates random deviates from GAMma distribution
Function
Generates random deviates from the gamma distribution whose
density is
(A**R)/Gamma(R) * X**(R-1) * Exp(-A*X)
Arguments
a --> Location parameter of Gamma distribution
r --> Shape parameter of Gamma distribution
Method
Renames SGAMMA from TOMS as slightly modified by BWB to use RANF
instead of SUNIF.
For details see:
(Case R >= 1.0)
Ahrens, J.H. and Dieter, U.
Generating Gamma Variates by a
Modified Rejection Technique.
Comm. ACM, 25,1 (Jan. 1982), 47 - 54.
Algorithm GD
(Case 0.0 <= R <= 1.0)
Ahrens, J.H. and Dieter, U.
Computer Methods for Sampling from Gamma,
Beta, Poisson and Binomial Distributions.
Computing, 12 (1974), 223-246/
Adapted algorithm GS.
**********************************************************************
*/
{
static float gengam;
gengam = sgamma(r);
gengam /= a;
return gengam;
}
void genmn(float *parm,float *x,float *work)
/*
**********************************************************************
void genmn(float *parm,float *x,float *work)
GENerate Multivariate Normal random deviate
Arguments
parm --> Parameters needed to generate multivariate normal
deviates (MEANV and Cholesky decomposition of
COVM). Set by a previous call to SETGMN.
1 : 1 - size of deviate, P
2 : P + 1 - mean vector
P+2 : P*(P+3)/2 + 1 - upper half of cholesky
decomposition of cov matrix
x <-- Vector deviate generated.
work <--> Scratch array
Method
1) Generate P independent standard normal deviates - Ei ~ N(0,1)
2) Using Cholesky decomposition find A s.t. trans(A)*A = COVM
3) trans(A)E + MEANV ~ N(MEANV,COVM)
**********************************************************************
*/
{
static long i,icount,j,p,D1,D2,D3,D4;
static float ae;
p = (long) (*parm);
/*
Generate P independent normal deviates - WORK ~ N(0,1)
*/
for(i=1; i<=p; i++) *(work+i-1) = snorm();
for(i=1,D3=1,D4=(p-i+D3)/D3; D4>0; D4--,i+=D3) {
/*
PARM (P+2 : P*(P+3)/2 + 1) contains A, the Cholesky
decomposition of the desired covariance matrix.
trans(A)(1,1) = PARM(P+2)
trans(A)(2,1) = PARM(P+3)
trans(A)(2,2) = PARM(P+2+P)
trans(A)(3,1) = PARM(P+4)
trans(A)(3,2) = PARM(P+3+P)
trans(A)(3,3) = PARM(P+2-1+2P) ...
trans(A)*WORK + MEANV ~ N(MEANV,COVM)
*/
icount = 0;
ae = 0.0;
for(j=1,D1=1,D2=(i-j+D1)/D1; D2>0; D2--,j+=D1) {
icount += (j-1);
ae += (*(parm+i+(j-1)*p-icount+p)**(work+j-1));
}
*(x+i-1) = ae+*(parm+i);
}
}
void genmul(long n,float *p,long ncat,long *ix)
/*
**********************************************************************
void genmul(int n,float *p,int ncat,int *ix)
GENerate an observation from the MULtinomial distribution
Arguments
N --> Number of events that will be classified into one of
the categories 1..NCAT
P --> Vector of probabilities. P(i) is the probability that
an event will be classified into category i. Thus, P(i)
must be [0,1]. Only the first NCAT-1 P(i) must be defined
since P(NCAT) is 1.0 minus the sum of the first
NCAT-1 P(i).
NCAT --> Number of categories. Length of P and IX.
IX <-- Observation from multinomial distribution. All IX(i)
will be nonnegative and their sum will be N.
Method
Algorithm from page 559 of
Devroye, Luc
Non-Uniform Random Variate Generation. Springer-Verlag,
New York, 1986.
**********************************************************************
*/
{
static float prob,ptot,sum;
static long i,icat,ntot;
if(n < 0) ftnstop("N < 0 in GENMUL");
if(ncat <= 1) ftnstop("NCAT <= 1 in GENMUL");
ptot = 0.0F;
for(i=0; i<ncat-1; i++) {
if(*(p+i) < 0.0F) ftnstop("Some P(i) < 0 in GENMUL");
if(*(p+i) > 1.0F) ftnstop("Some P(i) > 1 in GENMUL");
ptot += *(p+i);
}
if(ptot > 0.99999F) ftnstop("Sum of P(i) > 1 in GENMUL");
/*
Initialize variables
*/
ntot = n;
sum = 1.0F;
for(i=0; i<ncat; i++) ix[i] = 0;
/*
Generate the observation
*/
for(icat=0; icat<ncat-1; icat++) {
prob = *(p+icat)/sum;
*(ix+icat) = ignbin(ntot,prob);
ntot -= *(ix+icat);
if(ntot <= 0) return;
sum -= *(p+icat);
}
*(ix+ncat-1) = ntot;
/*
Finished
*/
return;
}
float gennch(float df,float xnonc)
/*
**********************************************************************
float gennch(float df,float xnonc)
Generate random value of Noncentral CHIsquare variable
Function
Generates random deviate from the distribution of a noncentral
chisquare with DF degrees of freedom and noncentrality parameter
xnonc.
Arguments
df --> Degrees of freedom of the chisquare
(Must be > 1.0)
xnonc --> Noncentrality parameter of the chisquare
(Must be >= 0.0)
Method
Uses fact that noncentral chisquare is the sum of a chisquare
deviate with DF-1 degrees of freedom plus the square of a normal
deviate with mean XNONC and standard deviation 1.
**********************************************************************
*/
{
static float gennch;
if(!(df <= 1.0 || xnonc < 0.0)) goto S10;
throw Exception("RANLIB Error:DF <= 1 or XNONC < 0 in GENNCH - ABORT");
S10:
gennch = genchi(df-1.0)+pow(gennor(sqrt(xnonc),1.0),2.0f);
return gennch;
}
float gennf(float dfn,float dfd,float xnonc)
/*
**********************************************************************
float gennf(float dfn,float dfd,float xnonc)
GENerate random deviate from the Noncentral F distribution
Function
Generates a random deviate from the noncentral F (variance ratio)
distribution with DFN degrees of freedom in the numerator, and DFD
degrees of freedom in the denominator, and noncentrality parameter
XNONC.
Arguments
dfn --> Numerator degrees of freedom
(Must be >= 1.0)
dfd --> Denominator degrees of freedom
(Must be positive)
xnonc --> Noncentrality parameter
(Must be nonnegative)
Method
Directly generates ratio of noncentral numerator chisquare variate
to central denominator chisquare variate.
**********************************************************************
*/
{
static float gennf,xden,xnum;
static long qcond;
qcond = dfn <= 1.0 || dfd <= 0.0 || xnonc < 0.0;
if(!qcond) goto S10;
throw Exception("RANLIB Error:In GENNF - Either (1) Numerator DF <= 1.0 or");
S10:
xnum = gennch(dfn,xnonc)/dfn;
/*
GENNF = ( GENNCH( DFN, XNONC ) / DFN ) / ( GENCHI( DFD ) / DFD )
*/
xden = genchi(dfd)/dfd;
if(!(xden <= 9.999999999998E-39*xnum)) goto S20;
gennf = 1.0E38;
goto S30;
S20:
gennf = xnum/xden;
S30:
return gennf;
}
float gennor(float av,float sd)
/*
**********************************************************************
float gennor(float av,float sd)
GENerate random deviate from a NORmal distribution
Function
Generates a single random deviate from a normal distribution
with mean, AV, and standard deviation, SD.
Arguments
av --> Mean of the normal distribution.
sd --> Standard deviation of the normal distribution.
Method
Renames SNORM from TOMS as slightly modified by BWB to use RANF
instead of SUNIF.
For details see:
Ahrens, J.H. and Dieter, U.
Extensions of Forsythe's Method for Random
Sampling from the Normal Distribution.
Math. Comput., 27,124 (Oct. 1973), 927 - 937.
**********************************************************************
*/
{
static float gennor;
gennor = sd*snorm()+av;
return gennor;
}
void genprm(long *iarray,int larray)
/*
**********************************************************************
void genprm(long *iarray,int larray)
GENerate random PeRMutation of iarray
Arguments
iarray <--> On output IARRAY is a random permutation of its
value on input
larray <--> Length of IARRAY
**********************************************************************
*/
{
static long i,itmp,iwhich,D1,D2;
for(i=1,D1=1,D2=(larray-i+D1)/D1; D2>0; D2--,i+=D1) {
iwhich = ignuin(i,larray);
itmp = *(iarray+iwhich-1);
*(iarray+iwhich-1) = *(iarray+i-1);
*(iarray+i-1) = itmp;
}
}
float genunf(float low,float high)
/*
**********************************************************************
float genunf(float low,float high)
GeNerate Uniform Real between LOW and HIGH
Function
Generates a real uniformly distributed between LOW and HIGH.
Arguments
low --> Low bound (exclusive) on real value to be generated
high --> High bound (exclusive) on real value to be generated
**********************************************************************
*/
{
static float genunf;
if(!(low > high)) goto S10;
throw Exception("RANLIB Error: LOW > HIGH in GENUNF");
S10:
genunf = low+(high-low)*ranf();
return genunf;
}
void gscgn(long getset,long *g)
/*
**********************************************************************
void gscgn(long getset,long *g)
Get/Set GeNerator
Gets or returns in G the number of the current generator
Arguments
getset --> 0 Get
1 Set
g <-- Number of the current random number generator (1..32)
**********************************************************************
*/
{
#define numg 32L
static long curntg = 1;
if(getset == 0) *g = curntg;
else {
if(*g < 0 || *g > numg)
throw Exception("RANLIB Error: Generator number out of range in GSCGN");
curntg = *g;
}
#undef numg
}
void gsrgs(long getset,long *qvalue)
/*
**********************************************************************
void gsrgs(long getset,long *qvalue)
Get/Set Random Generators Set
Gets or sets whether random generators set (initialized).
Initially (data statement) state is not set
If getset is 1 state is set to qvalue
If getset is 0 state returned in qvalue
**********************************************************************
*/
{
static long qinit = 0;
if(getset == 0) *qvalue = qinit;
else qinit = *qvalue;
}
void gssst(long getset,long *qset)
/*
**********************************************************************
void gssst(long getset,long *qset)
Get or Set whether Seed is Set
Initialize to Seed not Set
If getset is 1 sets state to Seed Set
If getset is 0 returns T in qset if Seed Set
Else returns F in qset
**********************************************************************
*/
{
static long qstate = 0;
if(getset != 0) qstate = 1;
else *qset = qstate;
}
long ignbin(long n,float pp)
/*
**********************************************************************
long ignbin(long n,float pp)
GENerate BINomial random deviate
Function
Generates a single random deviate from a binomial
distribution whose number of trials is N and whose
probability of an event in each trial is P.
Arguments
n --> The number of trials in the binomial distribution
from which a random deviate is to be generated.
p --> The probability of an event in each trial of the
binomial distribution from which a random deviate
is to be generated.
ignbin <-- A random deviate yielding the number of events
from N independent trials, each of which has
a probability of event P.
Method
This is algorithm BTPE from:
Kachitvichyanukul, V. and Schmeiser, B. W.
Binomial Random Variate Generation.
Communications of the ACM, 31, 2
(February, 1988) 216.
**********************************************************************
SUBROUTINE BTPEC(N,PP,ISEED,JX)
BINOMIAL RANDOM VARIATE GENERATOR
MEAN .LT. 30 -- INVERSE CDF
MEAN .GE. 30 -- ALGORITHM BTPE: ACCEPTANCE-REJECTION VIA
FOUR REGION COMPOSITION. THE FOUR REGIONS ARE A TRIANGLE
(SYMMETRIC IN THE CENTER), A PAIR OF PARALLELOGRAMS (ABOVE
THE TRIANGLE), AND EXPONENTIAL LEFT AND RIGHT TAILS.
BTPE REFERS TO BINOMIAL-TRIANGLE-PARALLELOGRAM-EXPONENTIAL.
BTPEC REFERS TO BTPE AND "COMBINED." THUS BTPE IS THE
RESEARCH AND BTPEC IS THE IMPLEMENTATION OF A COMPLETE
USABLE ALGORITHM.
REFERENCE: VORATAS KACHITVICHYANUKUL AND BRUCE SCHMEISER,
"BINOMIAL RANDOM VARIATE GENERATION,"
COMMUNICATIONS OF THE ACM, FORTHCOMING
WRITTEN: SEPTEMBER 1980.
LAST REVISED: MAY 1985, JULY 1987
REQUIRED SUBPROGRAM: RAND() -- A UNIFORM (0,1) RANDOM NUMBER
GENERATOR
ARGUMENTS
N : NUMBER OF BERNOULLI TRIALS (INPUT)
PP : PROBABILITY OF SUCCESS IN EACH TRIAL (INPUT)
ISEED: RANDOM NUMBER SEED (INPUT AND OUTPUT)
JX: RANDOMLY GENERATED OBSERVATION (OUTPUT)
VARIABLES
PSAVE: VALUE OF PP FROM THE LAST CALL TO BTPEC
NSAVE: VALUE OF N FROM THE LAST CALL TO BTPEC
XNP: VALUE OF THE MEAN FROM THE LAST CALL TO BTPEC
P: PROBABILITY USED IN THE GENERATION PHASE OF BTPEC
FFM: TEMPORARY VARIABLE EQUAL TO XNP + P
M: INTEGER VALUE OF THE CURRENT MODE
FM: FLOATING POINT VALUE OF THE CURRENT MODE
XNPQ: TEMPORARY VARIABLE USED IN SETUP AND SQUEEZING STEPS
P1: AREA OF THE TRIANGLE
C: HEIGHT OF THE PARALLELOGRAMS
XM: CENTER OF THE TRIANGLE
XL: LEFT END OF THE TRIANGLE
XR: RIGHT END OF THE TRIANGLE
AL: TEMPORARY VARIABLE
XLL: RATE FOR THE LEFT EXPONENTIAL TAIL
XLR: RATE FOR THE RIGHT EXPONENTIAL TAIL
P2: AREA OF THE PARALLELOGRAMS
P3: AREA OF THE LEFT EXPONENTIAL TAIL
P4: AREA OF THE RIGHT EXPONENTIAL TAIL
U: A U(0,P4) RANDOM VARIATE USED FIRST TO SELECT ONE OF THE
FOUR REGIONS AND THEN CONDITIONALLY TO GENERATE A VALUE
FROM THE REGION
V: A U(0,1) RANDOM NUMBER USED TO GENERATE THE RANDOM VALUE
(REGION 1) OR TRANSFORMED INTO THE VARIATE TO ACCEPT OR
REJECT THE CANDIDATE VALUE
IX: INTEGER CANDIDATE VALUE
X: PRELIMINARY CONTINUOUS CANDIDATE VALUE IN REGION 2 LOGIC
AND A FLOATING POINT IX IN THE ACCEPT/REJECT LOGIC
K: ABSOLUTE VALUE OF (IX-M)
F: THE HEIGHT OF THE SCALED DENSITY FUNCTION USED IN THE
ACCEPT/REJECT DECISION WHEN BOTH M AND IX ARE SMALL
ALSO USED IN THE INVERSE TRANSFORMATION
R: THE RATIO P/Q
G: CONSTANT USED IN CALCULATION OF PROBABILITY
MP: MODE PLUS ONE, THE LOWER INDEX FOR EXPLICIT CALCULATION
OF F WHEN IX IS GREATER THAN M
IX1: CANDIDATE VALUE PLUS ONE, THE LOWER INDEX FOR EXPLICIT
CALCULATION OF F WHEN IX IS LESS THAN M
I: INDEX FOR EXPLICIT CALCULATION OF F FOR BTPE
AMAXP: MAXIMUM ERROR OF THE LOGARITHM OF NORMAL BOUND
YNORM: LOGARITHM OF NORMAL BOUND
ALV: NATURAL LOGARITHM OF THE ACCEPT/REJECT VARIATE V
X1,F1,Z,W,Z2,X2,F2, AND W2 ARE TEMPORARY VARIABLES TO BE
USED IN THE FINAL ACCEPT/REJECT TEST
QN: PROBABILITY OF NO SUCCESS IN N TRIALS
REMARK
IX AND JX COULD LOGICALLY BE THE SAME VARIABLE, WHICH WOULD
SAVE A MEMORY POSITION AND A LINE OF CODE. HOWEVER, SOME
COMPILERS (E.G.,CDC MNF) OPTIMIZE BETTER WHEN THE ARGUMENTS
ARE NOT INVOLVED.
ISEED NEEDS TO BE DOUBLE PRECISION IF THE IMSL ROUTINE
GGUBFS IS USED TO GENERATE UNIFORM RANDOM NUMBER, OTHERWISE
TYPE OF ISEED SHOULD BE DICTATED BY THE UNIFORM GENERATOR
**********************************************************************
*****DETERMINE APPROPRIATE ALGORITHM AND WHETHER SETUP IS NECESSARY
*/
{
static float psave = -1.0;
static long nsave = -1;
static long ignbin,i,ix,ix1,k,m,mp,T1;
static float al,alv,amaxp,c,f,f1,f2,ffm,fm,g,p,p1,p2,p3,p4,q,qn,r,u,v,w,w2,x,x1,
x2,xl,xll,xlr,xm,xnp,xnpq,xr,ynorm,z,z2;
if(pp != psave) goto S10;
if(n != nsave) goto S20;
if(xnp < 30.0) goto S150;
goto S30;
S10:
/*
*****SETUP, PERFORM ONLY WHEN PARAMETERS CHANGE
*/
psave = pp;
p = min(psave,1.0-psave);
q = 1.0-p;
S20:
xnp = n*p;
nsave = n;
if(xnp < 30.0) goto S140;
ffm = xnp+p;
m = (long int) ffm;
fm = m;
xnpq = xnp*q;
p1 = (long) (2.195*sqrt(xnpq)-4.6*q)+0.5;
xm = fm+0.5;
xl = xm-p1;
xr = xm+p1;
c = 0.134+20.5/(15.3+fm);
al = (ffm-xl)/(ffm-xl*p);
xll = al*(1.0+0.5*al);
al = (xr-ffm)/(xr*q);
xlr = al*(1.0+0.5*al);
p2 = p1*(1.0+c+c);
p3 = p2+c/xll;
p4 = p3+c/xlr;
S30:
/*
*****GENERATE VARIATE
*/
u = ranf()*p4;
v = ranf();
/*
TRIANGULAR REGION
*/
if(u > p1) goto S40;
ix = (long int) (xm-p1*v+u);
goto S170;
S40:
/*
PARALLELOGRAM REGION
*/
if(u > p2) goto S50;
x = xl+(u-p1)/c;
v = v*c+1.0-ABS(xm-x)/p1;
if(v > 1.0 || v <= 0.0) goto S30;
ix = (long int) x;
goto S70;
S50:
/*
LEFT TAIL
*/
if(u > p3) goto S60;
ix = (long int) (xl+log(v)/xll);
if(ix < 0) goto S30;
v *= ((u-p2)*xll);
goto S70;
S60:
/*
RIGHT TAIL
*/
ix = (long int) (xr-log(v)/xlr);
if(ix > n) goto S30;
v *= ((u-p3)*xlr);
S70:
/*
*****DETERMINE APPROPRIATE WAY TO PERFORM ACCEPT/REJECT TEST
*/
k = ABS(ix-m);
if(k > 20 && k < xnpq/2-1) goto S130;
/*
EXPLICIT EVALUATION
*/
f = 1.0;
r = p/q;
g = (n+1)*r;
T1 = m-ix;
if(T1 < 0) goto S80;
else if(T1 == 0) goto S120;
else goto S100;
S80:
mp = m+1;
for(i=mp; i<=ix; i++) f *= (g/i-r);
goto S120;
S100:
ix1 = ix+1;
for(i=ix1; i<=m; i++) f /= (g/i-r);
S120:
if(v <= f) goto S170;
goto S30;
S130:
/*
SQUEEZING USING UPPER AND LOWER BOUNDS ON ALOG(F(X))
*/
amaxp = k/xnpq*((k*(k/3.0+0.625)+0.1666666666666)/xnpq+0.5);
ynorm = -(k*k/(2.0*xnpq));
alv = log(v);
if(alv < ynorm-amaxp) goto S170;
if(alv > ynorm+amaxp) goto S30;
/*
STIRLING'S FORMULA TO MACHINE ACCURACY FOR
THE FINAL ACCEPTANCE/REJECTION TEST
*/
x1 = ix+1.0;
f1 = fm+1.0;
z = n+1.0-fm;
w = n-ix+1.0;
z2 = z*z;
x2 = x1*x1;
f2 = f1*f1;
w2 = w*w;
if(alv <= xm*log(f1/x1)+(n-m+0.5)*log(z/w)+(ix-m)*log(w*p/(x1*q))+(13860.0-
(462.0-(132.0-(99.0-140.0/f2)/f2)/f2)/f2)/f1/166320.0+(13860.0-(462.0-
(132.0-(99.0-140.0/z2)/z2)/z2)/z2)/z/166320.0+(13860.0-(462.0-(132.0-
(99.0-140.0/x2)/x2)/x2)/x2)/x1/166320.0+(13860.0-(462.0-(132.0-(99.0
-140.0/w2)/w2)/w2)/w2)/w/166320.0) goto S170;
goto S30;
S140:
/*
INVERSE CDF LOGIC FOR MEAN LESS THAN 30
*/
qn = pow((double)q,(double)n);
r = p/q;
g = r*(n+1);
S150:
ix = 0;
f = qn;
u = ranf();
S160:
if(u < f) goto S170;
if(ix > 110) goto S150;
u -= f;
ix += 1;
f *= (g/ix-r);
goto S160;
S170:
if(psave > 0.5) ix = n-ix;
ignbin = ix;
return ignbin;
}
long ignnbn(long n,float p)
/*
**********************************************************************
long ignnbn(long n,float p)
GENerate Negative BiNomial random deviate
Function
Generates a single random deviate from a negative binomial
distribution.
Arguments
N --> The number of trials in the negative binomial distribution
from which a random deviate is to be generated.
P --> The probability of an event.
Method
Algorithm from page 480 of
Devroye, Luc
Non-Uniform Random Variate Generation. Springer-Verlag,
New York, 1986.
**********************************************************************
*/
{
static long ignnbn;
static float y,a,r;
/*
..
.. Executable Statements ..
*/
/*
Check Arguments
*/
if(n < 0) ftnstop("N < 0 in IGNNBN");
if(p <= 0.0F) ftnstop("P <= 0 in IGNNBN");
if(p >= 1.0F) ftnstop("P >= 1 in IGNNBN");
/*
Generate Y, a random gamma (n,(1-p)/p) variable
*/
r = (float)n;
a = p/(1.0F-p);
y = gengam(a,r);
/*
Generate a random Poisson(y) variable
*/
ignnbn = ignpoi(y);
return ignnbn;
}
long ignpoi(float mu)
/*
**********************************************************************
long ignpoi(float mu)
GENerate POIsson random deviate
Function
Generates a single random deviate from a Poisson
distribution with mean AV.
Arguments
av --> The mean of the Poisson distribution from which
a random deviate is to be generated.
genexp <-- The random deviate.
Method
Renames KPOIS from TOMS as slightly modified by BWB to use RANF
instead of SUNIF.
For details see:
Ahrens, J.H. and Dieter, U.
Computer Generation of Poisson Deviates
From Modified Normal Distributions.
ACM Trans. Math. Software, 8, 2
(June 1982),163-179
**********************************************************************
**********************************************************************
P O I S S O N DISTRIBUTION
**********************************************************************
**********************************************************************
FOR DETAILS SEE:
AHRENS, J.H. AND DIETER, U.
COMPUTER GENERATION OF POISSON DEVIATES
FROM MODIFIED NORMAL DISTRIBUTIONS.
ACM TRANS. MATH. SOFTWARE, 8,2 (JUNE 1982), 163 - 179.
(SLIGHTLY MODIFIED VERSION OF THE PROGRAM IN THE ABOVE ARTICLE)
**********************************************************************
INTEGER FUNCTION IGNPOI(IR,MU)
INPUT: IR=CURRENT STATE OF BASIC RANDOM NUMBER GENERATOR
MU=MEAN MU OF THE POISSON DISTRIBUTION
OUTPUT: IGNPOI=SAMPLE FROM THE POISSON-(MU)-DISTRIBUTION
MUPREV=PREVIOUS MU, MUOLD=MU AT LAST EXECUTION OF STEP P OR B.
TABLES: COEFFICIENTS A0-A7 FOR STEP F. FACTORIALS FACT
COEFFICIENTS A(K) - FOR PX = FK*V*V*SUM(A(K)*V**K)-DEL
SEPARATION OF CASES A AND B
*/
{
extern float fsign( float num, float sign );
static float a0 = -0.5;
static float a1 = 0.3333333;
static float a2 = -0.2500068;
static float a3 = 0.2000118;
static float a4 = -0.1661269;
static float a5 = 0.1421878;
static float a6 = -0.1384794;
static float a7 = 0.125006;
static float muold = 0.0;
static float muprev = 0.0;
static float fact[10] = {
1.0,1.0,2.0,6.0,24.0,120.0,720.0,5040.0,40320.0,362880.0
};
static long ignpoi,j,k,kflag,l,m;
static float b1,b2,c,c0,c1,c2,c3,d,del,difmuk,e,fk,fx,fy,g,omega,p,p0,px,py,q,s,
t,u,v,x,xx,pp[35];
if(mu == muprev) goto S10;
if(mu < 10.0) goto S120;
/*
C A S E A. (RECALCULATION OF S,D,L IF MU HAS CHANGED)
*/
muprev = mu;
s = sqrt(mu);
d = 6.0*mu*mu;
/*
THE POISSON PROBABILITIES PK EXCEED THE DISCRETE NORMAL
PROBABILITIES FK WHENEVER K >= M(MU). L=IFIX(MU-1.1484)
IS AN UPPER BOUND TO M(MU) FOR ALL MU >= 10 .
*/
l = (long) (mu-1.1484);
S10:
/*
STEP N. NORMAL SAMPLE - SNORM(IR) FOR STANDARD NORMAL DEVIATE
*/
g = mu+s*snorm();
if(g < 0.0) goto S20;
ignpoi = (long) (g);
/*
STEP I. IMMEDIATE ACCEPTANCE IF IGNPOI IS LARGE ENOUGH
*/
if(ignpoi >= l) return ignpoi;
/*
STEP S. SQUEEZE ACCEPTANCE - SUNIF(IR) FOR (0,1)-SAMPLE U
*/
fk = (float)ignpoi;
difmuk = mu-fk;
u = ranf();
if(d*u >= difmuk*difmuk*difmuk) return ignpoi;
S20:
/*
STEP P. PREPARATIONS FOR STEPS Q AND H.
(RECALCULATIONS OF PARAMETERS IF NECESSARY)
.3989423=(2*PI)**(-.5) .416667E-1=1./24. .1428571=1./7.
THE QUANTITIES B1, B2, C3, C2, C1, C0 ARE FOR THE HERMITE
APPROXIMATIONS TO THE DISCRETE NORMAL PROBABILITIES FK.
C=.1069/MU GUARANTEES MAJORIZATION BY THE 'HAT'-FUNCTION.
*/
if(mu == muold) goto S30;
muold = mu;
omega = 0.3989423/s;
b1 = 4.166667E-2/mu;
b2 = 0.3*b1*b1;
c3 = 0.1428571*b1*b2;
c2 = b2-15.0*c3;
c1 = b1-6.0*b2+45.0*c3;
c0 = 1.0-b1+3.0*b2-15.0*c3;
c = 0.1069/mu;
S30:
if(g < 0.0) goto S50;
/*
'SUBROUTINE' F IS CALLED (KFLAG=0 FOR CORRECT RETURN)
*/
kflag = 0;
goto S70;
S40:
/*
STEP Q. QUOTIENT ACCEPTANCE (RARE CASE)
*/
if(fy-u*fy <= py*exp(px-fx)) return ignpoi;
S50:
/*
STEP E. EXPONENTIAL SAMPLE - SEXPO(IR) FOR STANDARD EXPONENTIAL
DEVIATE E AND SAMPLE T FROM THE LAPLACE 'HAT'
(IF T <= -.6744 THEN PK < FK FOR ALL MU >= 10.)
*/
e = sexpo();
u = ranf();
u += (u-1.0);
t = 1.8+fsign(e,u);
if(t <= -0.6744) goto S50;
ignpoi = (long) (mu+s*t);
fk = (float)ignpoi;
difmuk = mu-fk;
/*
'SUBROUTINE' F IS CALLED (KFLAG=1 FOR CORRECT RETURN)
*/
kflag = 1;
goto S70;
S60:
/*
STEP H. HAT ACCEPTANCE (E IS REPEATED ON REJECTION)
*/
if(c*fabs(u) > py*exp(px+e)-fy*exp(fx+e)) goto S50;
return ignpoi;
S70:
/*
STEP F. 'SUBROUTINE' F. CALCULATION OF PX,PY,FX,FY.
CASE IGNPOI .LT. 10 USES FACTORIALS FROM TABLE FACT
*/
if(ignpoi >= 10) goto S80;
px = -mu;
py = pow((double)mu,(double)ignpoi)/ *(fact+ignpoi);
goto S110;
S80:
/*
CASE IGNPOI .GE. 10 USES POLYNOMIAL APPROXIMATION
A0-A7 FOR ACCURACY WHEN ADVISABLE
.8333333E-1=1./12. .3989423=(2*PI)**(-.5)
*/
del = 8.333333E-2/fk;
del -= (4.8*del*del*del);
v = difmuk/fk;
if(fabs(v) <= 0.25) goto S90;
px = fk*log(1.0+v)-difmuk-del;
goto S100;
S90:
px = fk*v*v*(((((((a7*v+a6)*v+a5)*v+a4)*v+a3)*v+a2)*v+a1)*v+a0)-del;
S100:
py = 0.3989423/sqrt(fk);
S110:
x = (0.5-difmuk)/s;
xx = x*x;
fx = -0.5*xx;
fy = omega*(((c3*xx+c2)*xx+c1)*xx+c0);
if(kflag <= 0) goto S40;
goto S60;
S120:
/*
C A S E B. (START NEW TABLE AND CALCULATE P0 IF NECESSARY)
*/
muprev = 0.0;
if(mu == muold) goto S130;
muold = mu;
m = max(1L,(long) (mu));
l = 0;
p = exp(-mu);
q = p0 = p;
S130:
/*
STEP U. UNIFORM SAMPLE FOR INVERSION METHOD
*/
u = ranf();
ignpoi = 0;
if(u <= p0) return ignpoi;
/*
STEP T. TABLE COMPARISON UNTIL THE END PP(L) OF THE
PP-TABLE OF CUMULATIVE POISSON PROBABILITIES
(0.458=PP(9) FOR MU=10)
*/
if(l == 0) goto S150;
j = 1;
if(u > 0.458) j = min(l,m);
for(k=j; k<=l; k++) {
if(u <= *(pp+k-1)) goto S180;
}
if(l == 35) goto S130;
S150:
/*
STEP C. CREATION OF NEW POISSON PROBABILITIES P
AND THEIR CUMULATIVES Q=PP(K)
*/
l += 1;
for(k=l; k<=35; k++) {
p = p*mu/(float)k;
q += p;
*(pp+k-1) = q;
if(u <= q) goto S170;
}
l = 35;
goto S130;
S170:
l = k;
S180:
ignpoi = k;
return ignpoi;
}
long ignuin(long low,long high)
/*
**********************************************************************
long ignuin(long low,long high)
GeNerate Uniform INteger
Function
Generates an integer uniformly distributed between LOW and HIGH.
Arguments
low --> Low bound (inclusive) on integer value to be generated
high --> High bound (inclusive) on integer value to be generated
Note
If (HIGH-LOW) > 2,147,483,561 prints error message on * unit and
stops the program.
**********************************************************************
IGNLGI generates integers between 1 and 2147483562
MAXNUM is 1 less than maximum generable value
*/
{
#define maxnum 2147483561L
static long ignuin,ign,maxnow,range,ranp1;
if(!(low > high)) goto S10;
throw Exception("RANLIB Error: low > high in ignuin - ABORT");
S10:
range = high-low;
if(!(range > maxnum)) goto S20;
throw Exception("RANLIB Error: high - low too large in ignuin - ABORT");
S20:
if(!(low == high)) goto S30;
ignuin = low;
return ignuin;
S30:
/*
Number to be generated should be in range 0..RANGE
Set MAXNOW so that the number of integers in 0..MAXNOW is an
integral multiple of the number in 0..RANGE
*/
ranp1 = range+1;
maxnow = maxnum/ranp1*ranp1;
S40:
ign = ignlgi()-1;
if(!(ign <= maxnow)) goto S50;
ignuin = low+ign%ranp1;
return ignuin;
S50:
goto S40;
#undef maxnum
#undef err1
#undef err2
}
long lennob( char *str )
/*
Returns the length of str ignoring trailing blanks but not
other white space.
*/
{
long i, i_nb;
for (i=0, i_nb= -1L; *(str+i); i++)
if ( *(str+i) != ' ' ) i_nb = i;
return (i_nb+1);
}
long mltmod(long a,long s,long m)
/*
**********************************************************************
long mltmod(long a,long s,long m)
Returns (A*S) MOD M
This is a transcription from Pascal to Fortran of routine
MULtMod_Decompos from the paper
L'Ecuyer, P. and Cote, S. "Implementing a Random Number Package
with Splitting Facilities." ACM Transactions on Mathematical
Software, 17:98-111 (1991)
Arguments
a, s, m -->
**********************************************************************
*/
{
#define h 32768L
static long mltmod,a0,a1,k,p,q,qh,rh;
/*
H = 2**((b-2)/2) where b = 32 because we are using a 32 bit
machine. On a different machine recompute H
*/
if(!(a <= 0 || a >= m || s <= 0 || s >= m)) goto S10;
throw Exception("RANLIB Error: mltmod requires: 0 < a < m; 0 < s < m");
S10:
if(!(a < h)) goto S20;
a0 = a;
p = 0;
goto S120;
S20:
a1 = a/h;
a0 = a-h*a1;
qh = m/h;
rh = m-h*qh;
if(!(a1 >= h)) goto S50;
a1 -= h;
k = s/qh;
p = h*(s-k*qh)-k*rh;
S30:
if(!(p < 0)) goto S40;
p += m;
goto S30;
S40:
goto S60;
S50:
p = 0;
S60:
/*
P = (A2*S*H)MOD M
*/
if(!(a1 != 0)) goto S90;
q = m/a1;
k = s/q;
p -= (k*(m-a1*q));
if(p > 0) p -= m;
p += (a1*(s-k*q));
S70:
if(!(p < 0)) goto S80;
p += m;
goto S70;
S90:
S80:
k = p/qh;
/*
P = ((A2*H + A1)*S)MOD M
*/
p = h*(p-k*qh)-k*rh;
S100:
if(!(p < 0)) goto S110;
p += m;
goto S100;
S120:
S110:
if(!(a0 != 0)) goto S150;
/*
P = ((A2*H + A1)*H*S)MOD M
*/
q = m/a0;
k = s/q;
p -= (k*(m-a0*q));
if(p > 0) p -= m;
p += (a0*(s-k*q));
S130:
if(!(p < 0)) goto S140;
p += m;
goto S130;
S150:
S140:
mltmod = p;
return mltmod;
#undef h
}
void phrtsd(char* phrase,long *seed1,long *seed2)
/*
**********************************************************************
void phrtsd(char* phrase,long *seed1,long *seed2)
PHRase To SeeDs
Function
Uses a phrase (character string) to generate two seeds for the RGN
random number generator.
Arguments
phrase --> Phrase to be used for random number generation
seed1 <-- First seed for generator
seed2 <-- Second seed for generator
Note
Trailing blanks are eliminated before the seeds are generated.
Generated seed values will fall in the range 1..2^30
(1..1,073,741,824)
**********************************************************************
*/
{
static char table[] =
"abcdefghijklmnopqrstuvwxyz\
ABCDEFGHIJKLMNOPQRSTUVWXYZ\
0123456789\
!@#$%^&*()_+[];:'\\\"<>?,./";
long ix;
static long twop30 = 1073741824L;
static long shift[5] = {
1L,64L,4096L,262144L,16777216L
};
static long i,ichr,j,lphr,values[5];
extern long lennob(char *str);
*seed1 = 1234567890L;
*seed2 = 123456789L;
lphr = lennob(phrase);
if(lphr < 1) return;
for(i=0; i<=(lphr-1); i++) {
for (ix=0; table[ix]; ix++) if (*(phrase+i) == table[ix]) break;
if (!table[ix]) ix = 0;
ichr = ix % 64;
if(ichr == 0) ichr = 63;
for(j=1; j<=5; j++) {
*(values+j-1) = ichr-j;
if(*(values+j-1) < 1) *(values+j-1) += 63;
}
for(j=1; j<=5; j++) {
*seed1 = ( *seed1+*(shift+j-1)**(values+j-1) ) % twop30;
*seed2 = ( *seed2+*(shift+j-1)**(values+6-j-1) ) % twop30;
}
}
#undef twop30
}
float ranf(void)
/*
**********************************************************************
float ranf(void)
RANDom number generator as a Function
Returns a random floating point number from a uniform distribution
over 0 - 1 (endpoints of this interval are not returned) using the
current generator
This is a transcription from Pascal to Fortran of routine
Uniform_01 from the paper
L'Ecuyer, P. and Cote, S. "Implementing a Random Number Package
with Splitting Facilities." ACM Transactions on Mathematical
Software, 17:98-111 (1991)
**********************************************************************
*/
{
static float ranf;
/*
4.656613057E-10 is 1/M1 M1 is set in a data statement in IGNLGI
and is currently 2147483563. If M1 changes, change this also.
*/
ranf = ignlgi()*4.656613057E-10;
return ranf;
}
float sexpo(void)
/*
**********************************************************************
(STANDARD-) E X P O N E N T I A L DISTRIBUTION
**********************************************************************
**********************************************************************
FOR DETAILS SEE:
AHRENS, J.H. AND DIETER, U.
COMPUTER METHODS FOR SAMPLING FROM THE
EXPONENTIAL AND NORMAL DISTRIBUTIONS.
COMM. ACM, 15,10 (OCT. 1972), 873 - 882.
ALL STATEMENT NUMBERS CORRESPOND TO THE STEPS OF ALGORITHM
'SA' IN THE ABOVE PAPER (SLIGHTLY MODIFIED IMPLEMENTATION)
Modified by Barry W. Brown, Feb 3, 1988 to use RANF instead of
SUNIF. The argument IR thus goes away.
**********************************************************************
Q(N) = SUM(ALOG(2.0)**K/K!) K=1,..,N , THE HIGHEST N
(HERE 8) IS DETERMINED BY Q(N)=1.0 WITHIN STANDARD PRECISION
*/
{
static float q[8] = {
0.6931472,0.9333737,0.9888778,0.9984959,0.9998293,0.9999833,0.9999986,1.0
};
static long i;
static float sexpo,a,u,ustar,umin;
static float *q1 = q;
a = 0.0;
u = ranf();
goto S30;
S20:
a += *q1;
S30:
u += u;
if(u <= 1.0) goto S20;
u -= 1.0;
if(u > *q1) goto S60;
sexpo = a+u;
return sexpo;
S60:
i = 1;
ustar = ranf();
umin = ustar;
S70:
ustar = ranf();
if(ustar < umin) umin = ustar;
i += 1;
if(u > *(q+i-1)) goto S70;
sexpo = a+umin**q1;
return sexpo;
}
float sgamma(float a)
/*
**********************************************************************
(STANDARD-) G A M M A DISTRIBUTION
**********************************************************************
**********************************************************************
PARAMETER A >= 1.0 !
**********************************************************************
FOR DETAILS SEE:
AHRENS, J.H. AND DIETER, U.
GENERATING GAMMA VARIATES BY A
MODIFIED REJECTION TECHNIQUE.
COMM. ACM, 25,1 (JAN. 1982), 47 - 54.
STEP NUMBERS CORRESPOND TO ALGORITHM 'GD' IN THE ABOVE PAPER
(STRAIGHTFORWARD IMPLEMENTATION)
Modified by Barry W. Brown, Feb 3, 1988 to use RANF instead of
SUNIF. The argument IR thus goes away.
**********************************************************************
PARAMETER 0.0 < A < 1.0 !
**********************************************************************
FOR DETAILS SEE:
AHRENS, J.H. AND DIETER, U.
COMPUTER METHODS FOR SAMPLING FROM GAMMA,
BETA, POISSON AND BINOMIAL DISTRIBUTIONS.
COMPUTING, 12 (1974), 223 - 246.
(ADAPTED IMPLEMENTATION OF ALGORITHM 'GS' IN THE ABOVE PAPER)
**********************************************************************
INPUT: A =PARAMETER (MEAN) OF THE STANDARD GAMMA DISTRIBUTION
OUTPUT: SGAMMA = SAMPLE FROM THE GAMMA-(A)-DISTRIBUTION
COEFFICIENTS Q(K) - FOR Q0 = SUM(Q(K)*A**(-K))
COEFFICIENTS A(K) - FOR Q = Q0+(T*T/2)*SUM(A(K)*V**K)
COEFFICIENTS E(K) - FOR EXP(Q)-1 = SUM(E(K)*Q**K)
PREVIOUS A PRE-SET TO ZERO - AA IS A', AAA IS A"
SQRT32 IS THE SQUAREROOT OF 32 = 5.656854249492380
*/
{
extern float fsign( float num, float sign );
static float q1 = 4.166669E-2;
static float q2 = 2.083148E-2;
static float q3 = 8.01191E-3;
static float q4 = 1.44121E-3;
static float q5 = -7.388E-5;
static float q6 = 2.4511E-4;
static float q7 = 2.424E-4;
static float a1 = 0.3333333;
static float a2 = -0.250003;
static float a3 = 0.2000062;
static float a4 = -0.1662921;
static float a5 = 0.1423657;
static float a6 = -0.1367177;
static float a7 = 0.1233795;
static float e1 = 1.0;
static float e2 = 0.4999897;
static float e3 = 0.166829;
static float e4 = 4.07753E-2;
static float e5 = 1.0293E-2;
static float aa = 0.0;
static float aaa = 0.0;
static float sqrt32 = 5.656854;
static float sgamma,s2,s,d,t,x,u,r,q0,b,si,c,v,q,e,w,p;
if(a == aa) goto S10;
if(a < 1.0) goto S120;
/*
STEP 1: RECALCULATIONS OF S2,S,D IF A HAS CHANGED
*/
aa = a;
s2 = a-0.5;
s = sqrt(s2);
d = sqrt32-12.0*s;
S10:
/*
STEP 2: T=STANDARD NORMAL DEVIATE,
X=(S,1/2)-NORMAL DEVIATE.
IMMEDIATE ACCEPTANCE (I)
*/
t = snorm();
x = s+0.5*t;
sgamma = x*x;
if(t >= 0.0) return sgamma;
/*
STEP 3: U= 0,1 -UNIFORM SAMPLE. SQUEEZE ACCEPTANCE (S)
*/
u = ranf();
if(d*u <= t*t*t) return sgamma;
/*
STEP 4: RECALCULATIONS OF Q0,B,SI,C IF NECESSARY
*/
if(a == aaa) goto S40;
aaa = a;
r = 1.0/ a;
q0 = ((((((q7*r+q6)*r+q5)*r+q4)*r+q3)*r+q2)*r+q1)*r;
/*
APPROXIMATION DEPENDING ON SIZE OF PARAMETER A
THE CONSTANTS IN THE EXPRESSIONS FOR B, SI AND
C WERE ESTABLISHED BY NUMERICAL EXPERIMENTS
*/
if(a <= 3.686) goto S30;
if(a <= 13.022) goto S20;
/*
CASE 3: A .GT. 13.022
*/
b = 1.77;
si = 0.75;
c = 0.1515/s;
goto S40;
S20:
/*
CASE 2: 3.686 .LT. A .LE. 13.022
*/
b = 1.654+7.6E-3*s2;
si = 1.68/s+0.275;
c = 6.2E-2/s+2.4E-2;
goto S40;
S30:
/*
CASE 1: A .LE. 3.686
*/
b = 0.463+s+0.178*s2;
si = 1.235;
c = 0.195/s-7.9E-2+1.6E-1*s;
S40:
/*
STEP 5: NO QUOTIENT TEST IF X NOT POSITIVE
*/
if(x <= 0.0) goto S70;
/*
STEP 6: CALCULATION OF V AND QUOTIENT Q
*/
v = t/(s+s);
if(fabs(v) <= 0.25) goto S50;
q = q0-s*t+0.25*t*t+(s2+s2)*log(1.0+v);
goto S60;
S50:
q = q0+0.5*t*t*((((((a7*v+a6)*v+a5)*v+a4)*v+a3)*v+a2)*v+a1)*v;
S60:
/*
STEP 7: QUOTIENT ACCEPTANCE (Q)
*/
if(log(1.0-u) <= q) return sgamma;
S70:
/*
STEP 8: E=STANDARD EXPONENTIAL DEVIATE
U= 0,1 -UNIFORM DEVIATE
T=(B,SI)-DOUBLE EXPONENTIAL (LAPLACE) SAMPLE
*/
e = sexpo();
u = ranf();
u += (u-1.0);
t = b+fsign(si*e,u);
/*
STEP 9: REJECTION IF T .LT. TAU(1) = -.71874483771719
*/
if(t < -0.7187449) goto S70;
/*
STEP 10: CALCULATION OF V AND QUOTIENT Q
*/
v = t/(s+s);
if(fabs(v) <= 0.25) goto S80;
q = q0-s*t+0.25*t*t+(s2+s2)*log(1.0+v);
goto S90;
S80:
q = q0+0.5*t*t*((((((a7*v+a6)*v+a5)*v+a4)*v+a3)*v+a2)*v+a1)*v;
S90:
/*
STEP 11: HAT ACCEPTANCE (H) (IF Q NOT POSITIVE GO TO STEP 8)
*/
if(q <= 0.0) goto S70;
if(q <= 0.5) goto S100;
w = exp(q)-1.0;
goto S110;
S100:
w = ((((e5*q+e4)*q+e3)*q+e2)*q+e1)*q;
S110:
/*
IF T IS REJECTED, SAMPLE AGAIN AT STEP 8
*/
if(c*fabs(u) > w*exp(e-0.5*t*t)) goto S70;
x = s+0.5*t;
sgamma = x*x;
return sgamma;
S120:
/*
ALTERNATE METHOD FOR PARAMETERS A BELOW 1 (.3678794=EXP(-1.))
*/
aa = 0.0;
b = 1.0+0.3678794*a;
S130:
p = b*ranf();
if(p >= 1.0) goto S140;
sgamma = exp(log(p)/ a);
if(sexpo() < sgamma) goto S130;
return sgamma;
S140:
sgamma = -log((b-p)/ a);
if(sexpo() < (1.0-a)*log(sgamma)) goto S130;
return sgamma;
}
float snorm(void)
/*
**********************************************************************
(STANDARD-) N O R M A L DISTRIBUTION
**********************************************************************
**********************************************************************
FOR DETAILS SEE:
AHRENS, J.H. AND DIETER, U.
EXTENSIONS OF FORSYTHE'S METHOD FOR RANDOM
SAMPLING FROM THE NORMAL DISTRIBUTION.
MATH. COMPUT., 27,124 (OCT. 1973), 927 - 937.
ALL STATEMENT NUMBERS CORRESPOND TO THE STEPS OF ALGORITHM 'FL'
(M=5) IN THE ABOVE PAPER (SLIGHTLY MODIFIED IMPLEMENTATION)
Modified by Barry W. Brown, Feb 3, 1988 to use RANF instead of
SUNIF. The argument IR thus goes away.
**********************************************************************
THE DEFINITIONS OF THE CONSTANTS A(K), D(K), T(K) AND
H(K) ARE ACCORDING TO THE ABOVEMENTIONED ARTICLE
*/
{
static float a[32] = {
0.0,3.917609E-2,7.841241E-2,0.11777,0.1573107,0.1970991,0.2372021,0.2776904,
0.3186394,0.36013,0.4022501,0.4450965,0.4887764,0.5334097,0.5791322,
0.626099,0.6744898,0.7245144,0.7764218,0.8305109,0.8871466,0.9467818,
1.00999,1.077516,1.150349,1.229859,1.318011,1.417797,1.534121,1.67594,
1.862732,2.153875
};
static float d[31] = {
0.0,0.0,0.0,0.0,0.0,0.2636843,0.2425085,0.2255674,0.2116342,0.1999243,
0.1899108,0.1812252,0.1736014,0.1668419,0.1607967,0.1553497,0.1504094,
0.1459026,0.14177,0.1379632,0.1344418,0.1311722,0.128126,0.1252791,
0.1226109,0.1201036,0.1177417,0.1155119,0.1134023,0.1114027,0.1095039
};
static float t[31] = {
7.673828E-4,2.30687E-3,3.860618E-3,5.438454E-3,7.0507E-3,8.708396E-3,
1.042357E-2,1.220953E-2,1.408125E-2,1.605579E-2,1.81529E-2,2.039573E-2,
2.281177E-2,2.543407E-2,2.830296E-2,3.146822E-2,3.499233E-2,3.895483E-2,
4.345878E-2,4.864035E-2,5.468334E-2,6.184222E-2,7.047983E-2,8.113195E-2,
9.462444E-2,0.1123001,0.136498,0.1716886,0.2276241,0.330498,0.5847031
};
static float h[31] = {
3.920617E-2,3.932705E-2,3.951E-2,3.975703E-2,4.007093E-2,4.045533E-2,
4.091481E-2,4.145507E-2,4.208311E-2,4.280748E-2,4.363863E-2,4.458932E-2,
4.567523E-2,4.691571E-2,4.833487E-2,4.996298E-2,5.183859E-2,5.401138E-2,
5.654656E-2,5.95313E-2,6.308489E-2,6.737503E-2,7.264544E-2,7.926471E-2,
8.781922E-2,9.930398E-2,0.11556,0.1404344,0.1836142,0.2790016,0.7010474
};
static long i;
static float snorm,u,s,ustar,aa,w,y,tt;
u = ranf();
s = 0.0;
if(u > 0.5) s = 1.0;
u += (u-s);
u = 32.0*u;
i = (long) (u);
if(i == 32) i = 31;
if(i == 0) goto S100;
/*
START CENTER
*/
ustar = u-(float)i;
aa = *(a+i-1);
S40:
if(ustar <= *(t+i-1)) goto S60;
w = (ustar-*(t+i-1))**(h+i-1);
S50:
/*
EXIT (BOTH CASES)
*/
y = aa+w;
snorm = y;
if(s == 1.0) snorm = -y;
return snorm;
S60:
/*
CENTER CONTINUED
*/
u = ranf();
w = u*(*(a+i)-aa);
tt = (0.5*w+aa)*w;
goto S80;
S70:
tt = u;
ustar = ranf();
S80:
if(ustar > tt) goto S50;
u = ranf();
if(ustar >= u) goto S70;
ustar = ranf();
goto S40;
S100:
/*
START TAIL
*/
i = 6;
aa = *(a+31);
goto S120;
S110:
aa += *(d+i-1);
i += 1;
S120:
u += u;
if(u < 1.0) goto S110;
u -= 1.0;
S140:
w = u**(d+i-1);
tt = (0.5*w+aa)*w;
goto S160;
S150:
tt = u;
S160:
ustar = ranf();
if(ustar > tt) goto S50;
u = ranf();
if(ustar >= u) goto S150;
u = ranf();
goto S140;
}
float fsign( float num, float sign )
/* Transfers sign of argument sign to argument num */
{
if ( ( sign>0.0f && num<0.0f ) || ( sign<0.0f && num>0.0f ) )
return -num;
else return num;
}
/************************************************************************
FTNSTOP:
Prints msg to standard error and then exits
************************************************************************/
void ftnstop(const char* msg)
/* msg - error message */
{
throw Exception(msg);
}
|