This file is indexed.

/usr/include/scythestat/distributions.h is in libscythestat-dev 1.0.2-1.

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
/* 
 * Scythe Statistical Library Copyright (C) 2000-2002 Andrew D. Martin
 * and Kevin M. Quinn; 2002-present Andrew D. Martin, Kevin M. Quinn,
 * and Daniel Pemstein.  All Rights Reserved.
 *
 * This program is free software; you can redistribute it and/or
 * modify under the terms of the GNU General Public License as
 * published by Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.  See the text files
 * COPYING and LICENSE, distributed with this source code, for further
 * information.
 * --------------------------------------------------------------------
 *  scythestat/distributions.h
 *
 */

/*!  \file distributions.h
 *
 * \brief Definitions for probability density functions
 * (PDFs), cumulative distribution functions (CDFs), and some common
 * functions (gamma, beta, etc).
 *
 * This file provides functions that evaluate the PDFs and CDFs of a
 * number of probability distributions.  In addition, it includes
 * definitions for another of related functions, such as the gamma
 * and beta functions.
 *
 * The various distribution functions in this file operate on both
 * scalar quantiles and matrices of quantiles and the
 * definitions of both forms of these functions appear below.  We
 * provide explicit documentation only for the scalar versions of the
 * these functions and describe the Matrix versions in the scalar
 * calls' documents.  Much like the operators in matrix.h, we
 * implement these overloaded versions of the distribution functions
 * in terms of both generalized and default templates to allow for
 * explicit control over the template type of the returned Matrix.
 *
 * \note Doxygen does not correctly expand the macro definitions we use
 * to generate the Matrix versions of the various distribution
 * functions.  Therefore, it incorrectly substitutes the macro
 * variable
 * __VA_ARGS__ for the actual parameter values in the parameter lists
 * of each of these functions.  For example, the definitions of the
 * Matrix versions of pbeta are listed as
 * \code
 * template<matrix_order RO, matrix_style RS, matrix_order PO, matrix_style PS>
 * Matrix<double, RO, RS> scythe::pbeta (const Matrix<double, PO, PS> &X, __VA_ARGS__)
 *
 * template<matrix_order O, matrix_style S>
 * Matrix<double, O, Concrete> scythe::pbeta (const Matrix<double, O, S> &X, __VA_ARGS__)
 * \endcode
 * when they should be
 * \code
 * template<matrix_order RO, matrix_style RS, matrix_order PO, matrix_style PS>
 * Matrix<double, RO, RS> scythe::pbeta (const Matrix<double, PO, PS> &X, double a, double b)
 *
 * template<matrix_order O, matrix_style S>
 * Matrix<double, O, Concrete> scythe::pbeta (const Matrix<double, O, S> &X, double a, double b)
 * \endcode
 *
 * \par
 * Furthermore, Doxygen erroneously lists a number of variables at the
 * end of this document that are not, in fact, declared in
 * distributions.h.  Again, this error is a result of Doxygen's macro
 * parsing capabilities.
 * 
 */

/* TODO: Figure out how to get doxygen to stop listing erroneous
 * variables at the end of the doc for this file.  They stem from it
 * misreading the nested macro calls used to generate matrix procs.
 */

/* TODO: Full R-style versions of these function including arbitrary
 * recycling of matrix arguments.  This is going to have to wait for
 * variadic templates to be doable without a complete mess.  There is
 * currently a variadic patch available for g++, perhaps we can add a
 * SCYTHE_VARIADIC flag and include these as option until they become
 * part of the standard in 2009.  Something to come back to after 1.0.
 */

#ifndef SCYTHE_DISTRIBUTIONS_H
#define SCYTHE_DISTRIBUTIONS_H

#include <iostream>
#include <cmath>
#include <cfloat>
#include <climits>
#include <algorithm>
#include <limits>

#ifdef HAVE_IEEEFP_H
#include <ieeefp.h>
#endif

#ifdef SCYTHE_COMPILE_DIRECT
#include "matrix.h"
#include "ide.h"
#include "error.h"
#else
#include "scythestat/matrix.h"
#include "scythestat/ide.h"
#include "scythestat/error.h"
#endif

/* Fill in some defs from R that aren't in math.h */
#ifndef M_PI
#define M_PI 3.141592653589793238462643383280
#endif
#define M_LN_SQRT_2PI 0.918938533204672741780329736406
#define M_LN_SQRT_PId2  0.225791352644727432363097614947
#define M_1_SQRT_2PI  0.39894228040143267793994605993
#define M_2PI   6.28318530717958647692528676655
#define M_SQRT_32 5.656854249492380195206754896838

#ifndef HAVE_TRUNC
/*! @cond */
inline double trunc(double x) throw ()
{
    if (x >= 0) 
      return std::floor(x);
    else
      return std::ceil(x);
}
/*! @endcond */
#endif

/* Many random number generators, pdfs, cdfs, and functions (gamma,
 * etc) in this file are based on code from the R Project, version
 * 1.6.0-1.7.1.  This code is available under the terms of the GNU
 * GPL.  Original copyright:
 *
 * Copyright (C) 1998      Ross Ihaka
 * Copyright (C) 2000-2002 The R Development Core Team
 * Copyright (C) 2003      The R Foundation
 */

namespace scythe {
  
  /*! @cond */
  
  /* Forward declarations */
  double gammafn (double);
  double lngammafn (double);
  double lnbetafn (double, double);
  double pgamma (double, double, double);
  double dgamma(double, double, double);
  double pnorm (double, double, double);

  /*! @endcond */

  /********************
   * Helper Functions *
   ********************/
  namespace {

    /* Evaluate a Chebysheve series at a given point */
    double
    chebyshev_eval (double x, const double *a, int n)
    {
      SCYTHE_CHECK_10(n < 1 || n > 1000, scythe_invalid_arg,
          "n not on [1, 1000]");
  
      SCYTHE_CHECK_10(x < -1.1 || x > 1.1, scythe_invalid_arg,
          "x not on [-1.1, 1.1]");
      
      double b0, b1, b2;
      b0 = b1 = b2 = 0;
  
      double twox = x * 2;
  
      for (int i = 1; i <= n; ++i) {
        b2 = b1;
        b1 = b0;
        b0 = twox * b1 - b2 + a[n - i];
      }
  
      return (b0 - b2) * 0.5;
    }

    /* Computes the log gamma correction factor for x >= 10 */
    double
    lngammacor(double x)
    {
      const double algmcs[15] = {
        +.1666389480451863247205729650822e+0,
        -.1384948176067563840732986059135e-4,
        +.9810825646924729426157171547487e-8,
        -.1809129475572494194263306266719e-10,
        +.6221098041892605227126015543416e-13,
      };
    
      SCYTHE_CHECK_10(x < 10, scythe_invalid_arg,
          "This function requires x >= 10");  
      SCYTHE_CHECK_10(x >= 3.745194030963158e306, scythe_range_error,
          "Underflow");
      
      if (x < 94906265.62425156) {
        double tmp = 10 / x;
        return chebyshev_eval(tmp * tmp * 2 - 1, algmcs, 5) / x;
      }
      
      return 1 / (x * 12);
    }

    /* Evaluates the "deviance part" */
    double
    bd0(double x, double np)
    {
      
      if(std::fabs(x - np) < 0.1 * (x + np)) {
        double v = (x - np) / (x + np);
        double s = (x - np) * v;
        double ej = 2 * x * v;
        v = v * v;
        for (int j = 1; ; j++) {
          ej *= v;
          double s1 = s + ej / ((j << 1) + 1);
          if (s1 == s)
            return s1;
          s = s1;
        }
      }
      
      return x * std::log(x / np) + np - x;
    }
  
    /* Computes the log of the error term in Stirling's formula */
    double
    stirlerr(double n)
    {
#define S0 0.083333333333333333333       /* 1/12 */
#define S1 0.00277777777777777777778     /* 1/360 */
#define S2 0.00079365079365079365079365  /* 1/1260 */
#define S3 0.000595238095238095238095238 /* 1/1680 */
#define S4 0.0008417508417508417508417508/* 1/1188 */
      
      /* error for 0, 0.5, 1.0, 1.5, ..., 14.5, 15.0 */
      const double sferr_halves[31] = {
        0.0, /* n=0 - wrong, place holder only */
        0.1534264097200273452913848,  /* 0.5 */
        0.0810614667953272582196702,  /* 1.0 */
        0.0548141210519176538961390,  /* 1.5 */
        0.0413406959554092940938221,  /* 2.0 */
        0.03316287351993628748511048, /* 2.5 */
        0.02767792568499833914878929, /* 3.0 */
        0.02374616365629749597132920, /* 3.5 */
        0.02079067210376509311152277, /* 4.0 */
        0.01848845053267318523077934, /* 4.5 */
        0.01664469118982119216319487, /* 5.0 */
        0.01513497322191737887351255, /* 5.5 */
        0.01387612882307074799874573, /* 6.0 */
        0.01281046524292022692424986, /* 6.5 */
        0.01189670994589177009505572, /* 7.0 */
        0.01110455975820691732662991, /* 7.5 */
        0.010411265261972096497478567, /* 8.0 */
        0.009799416126158803298389475, /* 8.5 */
        0.009255462182712732917728637, /* 9.0 */
        0.008768700134139385462952823, /* 9.5 */
        0.008330563433362871256469318, /* 10.0 */
        0.007934114564314020547248100, /* 10.5 */
        0.007573675487951840794972024, /* 11.0 */
        0.007244554301320383179543912, /* 11.5 */
        0.006942840107209529865664152, /* 12.0 */
        0.006665247032707682442354394, /* 12.5 */
        0.006408994188004207068439631, /* 13.0 */
        0.006171712263039457647532867, /* 13.5 */
        0.005951370112758847735624416, /* 14.0 */
        0.005746216513010115682023589, /* 14.5 */
        0.005554733551962801371038690  /* 15.0 */
      };
      double nn;
      
      if (n <= 15.0) {
        nn = n + n;
        if (nn == (int)nn)
          return(sferr_halves[(int)nn]);
        return (scythe::lngammafn(n + 1.) - (n + 0.5) * std::log(n) + n -
            std::log(std::sqrt(2 * M_PI)));
      }
      
      nn = n*n;
      if (n > 500)
        return((S0 - S1 / nn) / n);
      if (n > 80)
        return((S0 - (S1 - S2 / nn) / nn) / n);
      if (n > 35)
        return((S0 - (S1 - (S2 - S3 / nn) / nn) / nn) / n);
      /* 15 < n <= 35 : */
      return((S0 - (S1 - (S2 - (S3 - S4 / nn) / nn) / nn) / nn) / n);
#undef S1
#undef S2
#undef S3
#undef S4
    }


    /* Helper for dpois and dgamma */
    double
    dpois_raw (double x, double lambda)
    {
      if (lambda == 0)
        return ( (x == 0) ? 1.0 : 0.0);

      if (x == 0)
        return std::exp(-lambda);

      if (x < 0)
        return 0.0;

      return std::exp(-stirlerr(x) - bd0(x, lambda))
        / std::sqrt(2 * M_PI * x);
    }

  
    /* helper for pbeta */
    double
    pbeta_raw(double x, double pin, double qin)
    {
      double ans, c, finsum, p, ps, p1, q, term, xb, xi, y;
      int n, i, ib, swap_tail;
      
      const double eps = .5 * DBL_EPSILON;
      const double sml = DBL_MIN;
      const double lneps = std::log(eps);
      const double lnsml = std::log(eps);
      
      if (pin / (pin + qin) < x) {
        swap_tail = 1;
        y = 1 - x;
        p = qin;
        q = pin;
      } else {
        swap_tail=0;
        y = x;
        p = pin;
        q = qin;
      }
      
      if ((p + q) * y / (p + 1) < eps) {
        ans = 0;
        xb = p * std::log(std::max(y,sml)) - std::log(p) - lnbetafn(p,q);
        if (xb > lnsml && y != 0)
          ans = std::exp(xb);
        if (swap_tail)
          ans = 1-ans;
      } else {
        ps = q - std::floor(q);
        if (ps == 0)
          ps = 1;
        xb = p * std::log(y) - lnbetafn(ps, p) - std::log(p);
        ans = 0;
        if (xb >= lnsml) {
          ans = std::exp(xb);
          term = ans * p;
          if (ps != 1) {
            n = (int)std::max(lneps/std::log(y), 4.0);
            for(i = 1; i <= n; i++){
              xi = i;
              term *= (xi-ps)*y/xi;
              ans += term/(p+xi);
            }
          }
        }
        if (q > 1) {
          xb = p * std::log(y) + q * std::log(1 - y)
            - lnbetafn(p, q) - std::log(q);
          ib = (int) std::max(xb / lnsml, 0.0);
          term = std::exp(xb - ib * lnsml);
          c = 1 / (1 - y);
          p1 = q * c / (p + q - 1);
              
          finsum = 0;
          n = (int) q;
          if(q == n)
            n--;
          for (i = 1; i <= n; i++) {
            if(p1 <= 1 && term / eps <= finsum)
              break;
            xi = i;
            term = (q -xi + 1) * c * term / (p + q - xi);
            if (term > 1) {
              ib--;
              term *= sml;
            }
            if (ib == 0)
              finsum += term;
          }
          ans += finsum;
        }
        
        if(swap_tail)
          ans = 1-ans;
        ans = std::max(std::min(ans,1.),0.);
      }
      return ans;
    }
  
   /* Helper for dbinom */
    double
    dbinom_raw (double x, double n, double p, double q)
    { 
      double f, lc;

      if (p == 0)
        return((x == 0) ? 1.0 : 0.0);
      if (q == 0)
        return((x == n) ? 1.0 : 0.0);

      if (x == 0) { 
        if(n == 0)
          return 1.0;
        
        lc = (p < 0.1) ? -bd0(n, n * q) - n * p : n * std::log(q);
        return(std::exp(lc));
      }
      if (x == n) { 
        lc = (q < 0.1) ? -bd0(n,n * p) - n * q : n * std::log(p);
        return(std::exp(lc));
      }

      if (x < 0 || x > n)
        return 0.0;

      lc = stirlerr(n) - stirlerr(x) - stirlerr(n-x) - bd0(x,n*p) -
        bd0(n - x, n * q);
      
      f = (M_2PI * x * (n-x)) / n;

      return (std::exp(lc) / std::sqrt(f));
    }

    /* The normal probability density function implementation. */

#define SIXTEN 16
#define do_del(X)              \
    xsq = trunc(X * SIXTEN) / SIXTEN;        \
    del = (X - xsq) * (X + xsq);          \
    if(log_p) {              \
        *cum = (-xsq * xsq * 0.5) + (-del * 0.5) + std::log(temp);  \
        if((lower && x > 0.) || (upper && x <= 0.))      \
        *ccum = ::log1p(-std::exp(-xsq * xsq * 0.5) *     \
          std::exp(-del * 0.5) * temp);    \
    }                \
    else {                \
        *cum = std::exp(-xsq * xsq * 0.5) * std::exp(-del * 0.5) * temp;  \
        *ccum = 1.0 - *cum;            \
    }

#define swap_tail            \
    if (x > 0.) {/* swap  ccum <--> cum */      \
        temp = *cum; if(lower) *cum = *ccum; *ccum = temp;  \
    }

    void
    pnorm_both(double x, double *cum, double *ccum, int i_tail,
                bool log_p)
    {
      const double a[5] = {
        2.2352520354606839287,
        161.02823106855587881,
        1067.6894854603709582,
        18154.981253343561249,
        0.065682337918207449113
      };
      const double b[4] = {
        47.20258190468824187,
        976.09855173777669322,
        10260.932208618978205,
        45507.789335026729956
      };
      const double c[9] = {
        0.39894151208813466764,
        8.8831497943883759412,
        93.506656132177855979,
        597.27027639480026226,
        2494.5375852903726711,
        6848.1904505362823326,
        11602.651437647350124,
        9842.7148383839780218,
        1.0765576773720192317e-8
      };
      const double d[8] = {
        22.266688044328115691,
        235.38790178262499861,
        1519.377599407554805,
        6485.558298266760755,
        18615.571640885098091,
        34900.952721145977266,
        38912.003286093271411,
        19685.429676859990727
      };
      const double p[6] = {
        0.21589853405795699,
        0.1274011611602473639,
        0.022235277870649807,
        0.001421619193227893466,
        2.9112874951168792e-5,
        0.02307344176494017303
      };
      const double q[5] = {
        1.28426009614491121,
        0.468238212480865118,
        0.0659881378689285515,
        0.00378239633202758244,
        7.29751555083966205e-5
      };
      
      double xden, xnum, temp, del, eps, xsq, y;
      int i, lower, upper;

      /* Consider changing these : */
      eps = DBL_EPSILON * 0.5;

      /* i_tail in {0,1,2} =^= {lower, upper, both} */
      lower = i_tail != 1;
      upper = i_tail != 0;

      y = std::fabs(x);
      if (y <= 0.67448975) {
        /* qnorm(3/4) = .6744.... -- earlier had 0.66291 */
        if (y > eps) {
          xsq = x * x;
          xnum = a[4] * xsq;
          xden = xsq;
          for (i = 0; i < 3; ++i) {
            xnum = (xnum + a[i]) * xsq;
            xden = (xden + b[i]) * xsq;
          }
        } else xnum = xden = 0.0;
        
        temp = x * (xnum + a[3]) / (xden + b[3]);
        if(lower)  *cum = 0.5 + temp;
        if(upper) *ccum = 0.5 - temp;
        if(log_p) {
          if(lower)  *cum = std::log(*cum);
          if(upper) *ccum = std::log(*ccum);
        }
      } else if (y <= M_SQRT_32) {
        /* Evaluate pnorm for 0.674.. = qnorm(3/4) < |x| <= sqrt(32) 
         * ~= 5.657 */

        xnum = c[8] * y;
        xden = y;
        for (i = 0; i < 7; ++i) {
          xnum = (xnum + c[i]) * y;
          xden = (xden + d[i]) * y;
        }
        temp = (xnum + c[7]) / (xden + d[7]);
        do_del(y);
        swap_tail;
      } else if (log_p
                || (lower && -37.5193 < x && x < 8.2924)
                || (upper && -8.2929 < x && x < 37.5193)
          ) {
        /* Evaluate pnorm for x in (-37.5, -5.657) union (5.657, 37.5) */
        xsq = 1.0 / (x * x);
        xnum = p[5] * xsq;
        xden = xsq;
        for (i = 0; i < 4; ++i) {
          xnum = (xnum + p[i]) * xsq;
          xden = (xden + q[i]) * xsq;
        }
        temp = xsq * (xnum + p[4]) / (xden + q[4]);
        temp = (M_1_SQRT_2PI - temp) / y;
        do_del(x);
        swap_tail;
      } else {
        if (x > 0) {
          *cum = 1.;
          *ccum = 0.;
        } else {
          *cum = 0.;
          *ccum = 1.;
        }
        SCYTHE_THROW_10(scythe_convergence_error, "Did not converge");
      }

      return;
    }
#undef SIXTEN
#undef do_del
#undef swap_tail

    /* The standard normal distribution function */
    double
    pnorm1 (double x, bool lower_tail, bool log_p)
    {
      SCYTHE_CHECK_10(! finite(x), scythe_invalid_arg,
          "Quantile x is inifinte (+/-Inf) or NaN");

      double p, cp;
      pnorm_both(x, &p, &cp, (lower_tail ? 0 : 1), log_p);

      return (lower_tail ? p : cp);
    }
  } // anonymous namespace

  /*************
   * Functions *
   *************/
  
  /* The gamma function */

  /*! \brief The gamma function.
   *
   * Computes the gamma function, evaluated at \a x.
   *
   * \param x The value to compute gamma at.
   *
   * \see lngammafn(double x)
   * \see pgamma(double x, double shape, double scale)
   * \see dgamma(double x, double shape, double scale)
   * \see rng::rgamma(double shape, double scale)
   *
   * \throw scythe_range_error (Level 1)
   * \throw scythe_precision_error (Level 1)
   */
  inline double 
  gammafn (double x)
  {
    const double gamcs[22] = {
      +.8571195590989331421920062399942e-2,
      +.4415381324841006757191315771652e-2,
      +.5685043681599363378632664588789e-1,
      -.4219835396418560501012500186624e-2,
      +.1326808181212460220584006796352e-2,
      -.1893024529798880432523947023886e-3,
      +.3606925327441245256578082217225e-4,
      -.6056761904460864218485548290365e-5,
      +.1055829546302283344731823509093e-5,
      -.1811967365542384048291855891166e-6,
      +.3117724964715322277790254593169e-7,
      -.5354219639019687140874081024347e-8,
      +.9193275519859588946887786825940e-9,
      -.1577941280288339761767423273953e-9,
      +.2707980622934954543266540433089e-10,
      -.4646818653825730144081661058933e-11,
      +.7973350192007419656460767175359e-12,
      -.1368078209830916025799499172309e-12,
      +.2347319486563800657233471771688e-13,
      -.4027432614949066932766570534699e-14,
      +.6910051747372100912138336975257e-15,
      -.1185584500221992907052387126192e-15,
    };


    double y = std::fabs(x);

    if (y <= 10) {

      /* Compute gamma(x) for -10 <= x <= 10
       * Reduce the interval and find gamma(1 + y) for 0 <= y < 1
       * first of all. */

      int n = (int) x;
      if (x < 0)
        --n;
      
      y = x - n;/* n = floor(x)  ==>  y in [ 0, 1 ) */
      --n;
      double value = chebyshev_eval(y * 2 - 1, gamcs, 22) + .9375;
      
      if (n == 0)
        return value;/* x = 1.dddd = 1+y */

      if (n < 0) {
        /* compute gamma(x) for -10 <= x < 1 */

        /* If the argument is exactly zero or a negative integer */
        /* then return NaN. */
        SCYTHE_CHECK_10(x == 0 || (x < 0 && x == n + 2),
            scythe_range_error, "x is 0 or a negative integer");

        /* The answer is less than half precision */
        /* because x too near a negative integer. */
        SCYTHE_CHECK_10(x < -0.5 && 
            std::fabs(x - (int)(x - 0.5) / x) < 67108864.0,
            scythe_precision_error,
            "Answer < 1/2 precision because x is too near" <<
            " a negative integer");

        /* The argument is so close to 0 that the result
         * * would overflow. */
        SCYTHE_CHECK_10(y < 2.2474362225598545e-308, scythe_range_error,
            "x too close to 0");

        n = -n;

        for (int i = 0; i < n; i++)
          value /= (x + i);
        
        return value;
      } else {
        /* gamma(x) for 2 <= x <= 10 */

        for (int i = 1; i <= n; i++) {
          value *= (y + i);
        }
        return value;
      }
    } else {
      /* gamma(x) for   y = |x| > 10. */

      /* Overflow */
      SCYTHE_CHECK_10(x > 171.61447887182298, 
          scythe_range_error,"Overflow");

      /* Underflow */
      SCYTHE_CHECK_10(x < -170.5674972726612,
          scythe_range_error, "Underflow");

      double value = std::exp((y - 0.5) * std::log(y) - y 
          + M_LN_SQRT_2PI + lngammacor(y));

      if (x > 0)
        return value;

      SCYTHE_CHECK_10(std::fabs((x - (int)(x - 0.5))/x) < 67108864.0,
          scythe_precision_error, 
          "Answer < 1/2 precision because x is " <<
            "too near a negative integer");

      double sinpiy = std::sin(M_PI * y);

      /* Negative integer arg - overflow */
      SCYTHE_CHECK_10(sinpiy == 0, scythe_range_error, "Overflow");

      return -M_PI / (y * sinpiy * value);
    }
  }

  /* The natural log of the absolute value of the gamma function */
  /*! \brief The natural log of the absolute value of the gamma 
   * function.
   *
   * Computes the natural log of the absolute value of the gamma 
   * function, evaluated at \a x.
   *
   * \param x The value to compute log(abs(gamma())) at.
   *
   * \see gammafn(double x)
   * \see pgamma(double x, double shape, double scale)
   * \see dgamma(double x, double shape, double scale)
   * \see rng::rgamma(double shape, double scale)
   *
   * \throw scythe_range_error (Level 1)
   * \throw scythe_precision_error (Level 1)
   */
  inline double
  lngammafn(double x)
  {
    SCYTHE_CHECK_10(x <= 0 && x == (int) x, scythe_range_error,
        "x is 0 or a negative integer");

    double y = std::fabs(x);

    if (y <= 10)
      return std::log(std::fabs(gammafn(x)));

    SCYTHE_CHECK_10(y > 2.5327372760800758e+305, scythe_range_error,
        "Overflow");

    if (x > 0) /* i.e. y = x > 10 */
      return M_LN_SQRT_2PI + (x - 0.5) * std::log(x) - x
        + lngammacor(x);
    
    /* else: x < -10; y = -x */
    double sinpiy = std::fabs(std::sin(M_PI * y));

    if (sinpiy == 0) /* Negative integer argument */
      throw scythe_exception("UNEXPECTED ERROR",
           __FILE__, __func__, __LINE__,
           "ERROR:  Should never happen!");

    double ans = M_LN_SQRT_PId2 + (x - 0.5) * std::log(y) - x - std::log(sinpiy)
      - lngammacor(y);

    SCYTHE_CHECK_10(std::fabs((x - (int)(x - 0.5)) * ans / x) 
        < 1.490116119384765696e-8, scythe_precision_error, 
        "Answer < 1/2 precision because x is " 
        << "too near a negative integer");
    
    return ans;
  }

  /* The beta function */
  /*! \brief The beta function.
   *
   * Computes beta function, evaluated at (\a a, \a b).
   *
   * \param a The first parameter.
   * \param b The second parameter.
   *
   * \see lnbetafn(double a, double b)
   * \see pbeta(double x, double a, double b)
   * \see dbeta(double x, double a, double b)
   * \see rng::rbeta(double a, double b)
   *
   * \throw scythe_invalid_arg (Level 1)
   * \throw scythe_range_error (Level 1)
   * \throw scythe_precision_error (Level 1)
   */
  inline double
  betafn(double a, double b)
  {
    SCYTHE_CHECK_10(a <= 0 || b <= 0, scythe_invalid_arg, "a or b < 0");

    if (a + b < 171.61447887182298) /* ~= 171.61 for IEEE */
      return gammafn(a) * gammafn(b) / gammafn(a+b);

    double val = lnbetafn(a, b);
    SCYTHE_CHECK_10(val < -708.39641853226412, scythe_range_error,
        "Underflow");
    
    return std::exp(val);
  }

  /* The natural log of the beta function */
  /*! \brief The natural log of the beta function.
   *
   * Computes the natural log of the beta function, 
   * evaluated at (\a a, \a b).
   *
   * \param a The first parameter.
   * \param b The second parameter.
   *
   * \see betafn(double a, double b)
   * \see pbeta(double x, double a, double b)
   * \see dbeta(double x, double a, double b)
   * \see rng::rbeta(double a, double b)
   *
   * \throw scythe_invalid_arg (Level 1)
   * \throw scythe_range_error (Level 1)
   * \throw scythe_precision_error (Level 1)
   */
  inline double
  lnbetafn (double a, double b)
  {
    double p, q;

    p = q = a;
    if(b < p) p = b;/* := min(a,b) */
    if(b > q) q = b;/* := max(a,b) */

    SCYTHE_CHECK_10(p <= 0 || q <= 0,scythe_invalid_arg, "a or b <= 0");

    if (p >= 10) {
      /* p and q are big. */
      double corr = lngammacor(p) + lngammacor(q) - lngammacor(p + q);
      return std::log(q) * -0.5 + M_LN_SQRT_2PI + corr
        + (p - 0.5) * std::log(p / (p + q)) + q * std::log(1 + (-p / (p + q)));
    } else if (q >= 10) {
      /* p is small, but q is big. */
      double corr = lngammacor(q) - lngammacor(p + q);
      return lngammafn(p) + corr + p - p * std::log(p + q)
        + (q - 0.5) * std::log(1 + (-p / (p + q)));
    }
    
    /* p and q are small: p <= q > 10. */
    return std::log(gammafn(p) * (gammafn(q) / gammafn(p + q)));
  }

  /* Compute the factorial of a non-negative integer */
  /*! \brief The factorial function.
   *
   * Computes the factorial of \a n.
   *
   * \param n The non-negative integer value to compute the factorial of.
   *
   * \see lnfactorial(unsigned int n)
   *
   */
  inline int
  factorial (unsigned int n)
  {
    if (n == 0)
      return 1;

    return n * factorial(n - 1);
  }

  /* Compute the natural log of the factorial of a non-negative
   * integer
   */
  /*! \brief The log of the factorial function.
   *
   * Computes the natural log of the factorial of \a n.
   *
   * \param n The non-negative integer value to compute the natural log of the factorial of.
   *
   * \see factorial(unsigned int n)
   *
   */
  inline double
  lnfactorial (unsigned int n)
  {
    double x = n+1;
    double cof[6] = {
      76.18009172947146, -86.50532032941677,
      24.01409824083091, -1.231739572450155,
      0.1208650973866179e-2, -0.5395239384953e-5
    };
    double y = x;
    double tmp = x + 5.5 - (x + 0.5) * std::log(x + 5.5);
    double ser = 1.000000000190015;
    for (int j = 0; j <= 5; j++) {
      ser += (cof[j] / ++y);
    }
    return(std::log(2.5066282746310005 * ser / x) - tmp);
  }

  /*********************************
   * Fully Specified Distributions * 
   *********************************/

  /* These macros provide a nice shorthand for the matrix versions of
   * the pdf and cdf functions.
   */
 
#define SCYTHE_ARGSET(...) __VA_ARGS__

#define SCYTHE_DISTFUN_MATRIX(NAME, XTYPE, ARGNAMES, ...)             \
  template <matrix_order RO, matrix_style RS,                         \
            matrix_order PO, matrix_style PS>                         \
  Matrix<double, RO, RS>                                              \
  NAME (const Matrix<XTYPE, PO, PS>& X, __VA_ARGS__)                  \
  {                                                                   \
    Matrix<double, RO, Concrete> ret(X.rows(), X.cols(), false);      \
    const_matrix_forward_iterator<XTYPE,RO,PO,PS> xit;                \
    const_matrix_forward_iterator<XTYPE,RO,PO,PS> xlast               \
      = X.template end_f<RO>();                                       \
    typename Matrix<double,RO,Concrete>::forward_iterator rit         \
      = ret.begin_f();                                                \
    for (xit = X.template begin_f<RO>(); xit != xlast; ++xit) {       \
      *rit = NAME (*xit, ARGNAMES);                                   \
      ++rit;                                                          \
    }                                                                 \
    SCYTHE_VIEW_RETURN(double, RO, RS, ret)                           \
  }                                                                   \
                                                                      \
  template <matrix_order O, matrix_style S>                           \
  Matrix<double, O, Concrete>                                         \
  NAME (const Matrix<XTYPE, O, S>& X, __VA_ARGS__)                    \
  {                                                                   \
    return NAME <O, Concrete, O, S> (X, ARGNAMES);                    \
  }

  /**** The Beta Distribution ****/

  /* CDFs */

  /*! \brief The beta distribution function.
   *
   * Computes the value of the beta cumulative distribution function
   * with shape parameters \a a and \a b at the desired quantile,
   * \a x.
   *
   * It is also possible to call this function with a Matrix of
   * doubles as its first argument.  In this case the function will
   * return a Matrix of doubles of the same dimension as \a x,
   * containing the result of evaluating this function at each value
   * in \a x, given the remaining fixed parameters.  By default, the
   * returned Matrix will be concrete and have the same matrix_order
   * as \a x, but you may invoke a generalized version of the function
   * with an explicit template call.
   *
   * \param x The desired quantile, between 0 and 1.
   * \param a The first non-negative beta shape parameter.
   * \param b The second non-negative beta shape parameter.
   *
   * \see dbeta(double x, double a, double b)
   * \see rng::rbeta(double a, double b)
   * \see betafn(double a, double b)
   * \see lnbetafn(double a, double b)
   *
   * \throw scythe_invalid_arg (Level 1)
   * \throw scythe_range_error (Level 1)
   * \throw scythe_precision_error (Level 1)
   */
  inline double
  pbeta(double x, double a, double b)
  {
    SCYTHE_CHECK_10(a <= 0 || b <= 0,scythe_invalid_arg, "a or b <= 0");
    
    if (x <= 0)
      return 0.;
    if (x >= 1)
      return 1.;
    
    return pbeta_raw(x,a,b);
  }

  SCYTHE_DISTFUN_MATRIX(pbeta, double, SCYTHE_ARGSET(a, b), double a, double b)

  /* PDFs */
  /*! \brief The beta density function.
   *
   * Computes the value of the beta probability density function
   * with shape parameters \a a and \a b at the desired quantile,
   * \a x.
   *
   * It is also possible to call this function with a Matrix of
   * doubles as its first argument.  In this case the function will
   * return a Matrix of doubles of the same dimension as \a x,
   * containing the result of evaluating this function at each value
   * in \a x, given the remaining fixed parameters.  By default, the
   * returned Matrix will be concrete and have the same matrix_order
   * as \a x, but you may invoke a generalized version of the function
   * with an explicit template call.
   *
   * \param x The desired quantile, between 0 and 1.
   * \param a The first non-negative beta shape parameter.
   * \param b The second non-negative beta shape parameter.
   *
   * \see pbeta(double x, double a, double b)
   * \see rng::rbeta(double a, double b)
   * \see betafn(double a, double b)
   * \see lnbetafn(double a, double b)
   *
   * \throw scythe_invalid_arg (Level 1)
   * \throw scythe_range_error (Level 1)
   * \throw scythe_precision_error (Level 1)
   */
  inline double
  dbeta(double x, double a, double b)
  {
    SCYTHE_CHECK_10((x < 0.0) || (x > 1.0), scythe_invalid_arg,
        "x not in [0,1]");
    SCYTHE_CHECK_10(a < 0.0, scythe_invalid_arg, "a < 0");
    SCYTHE_CHECK_10(b < 0.0, scythe_invalid_arg, "b < 0");

    return (std::pow(x, (a-1.0)) * std::pow((1.0-x), (b-1.0)) )
      / betafn(a,b);
  }

  SCYTHE_DISTFUN_MATRIX(dbeta, double, SCYTHE_ARGSET(a, b), double a, double b)

  /* Returns the natural log of the ordinate of the Beta density
   * evaluated at x with Shape1 a, and Shape2 b
   */

  /*! \brief The natural log of the ordinate of the beta density
   * function.
   *
   * Computes the value of the natural log of the ordinate of the beta
   * probability density function
   * with shape parameters \a a and \a b at the desired quantile,
   * \a x.
   *
   * It is also possible to call this function with a Matrix of
   * doubles as its first argument.  In this case the function will
   * return a Matrix of doubles of the same dimension as \a x,
   * containing the result of evaluating this function at each value
   * in \a x, given the remaining fixed parameters.  By default, the
   * returned Matrix will be concrete and have the same matrix_order
   * as \a x, but you may invoke a generalized version of the function
   * with an explicit template call.
   *
   * \param x The desired quantile, between 0 and 1.
   * \param a The first non-negative beta shape parameter.
   * \param b The second non-negative beta shape parameter.
   *
   * \see dbeta(double x, double a, double b)
   *
   * \throw scythe_invalid_arg (Level 1)
   * \throw scythe_range_error (Level 1)
   * \throw scythe_precision_error (Level 1)
   */
  inline double
  lndbeta1(double x, double a, double b)
  { 
    SCYTHE_CHECK_10((x < 0.0) || (x > 1.0), scythe_invalid_arg,
        "x not in [0,1]");
    SCYTHE_CHECK_10(a < 0.0, scythe_invalid_arg, "a < 0");
    SCYTHE_CHECK_10(b < 0.0, scythe_invalid_arg, "b < 0");

    return (a-1.0) * std::log(x) + (b-1) * std::log(1.0-x)
      - lnbetafn(a,b);
  }

  SCYTHE_DISTFUN_MATRIX(lndbeta1, double, SCYTHE_ARGSET(a, b), double a, double b)


  /**** The Binomial Distribution ****/

  /* CDFs */

  /*! \brief The binomial distribution function.
   *
   * Computes the value of the binomial cumulative distribution function
   * with \a n trials and \a p probability of success on each trial,
   * at the desired quantile \a x.
   *
   * It is also possible to call this function with a Matrix of
   * doubles as its first argument.  In this case the function will
   * return a Matrix of doubles of the same dimension as \a x,
   * containing the result of evaluating this function at each value
   * in \a x, given the remaining fixed parameters.  By default, the
   * returned Matrix will be concrete and have the same matrix_order
   * as \a x, but you may invoke a generalized version of the function
   * with an explicit template call.
   *
   * \param x The desired quantile.
   * \param n The number of trials.
   * \param p The probability of success on each trial.
   *
   * \see dbinom(double x, unsigned int n, double p)
   * \see rng::rbinom(unsigned int n, double p)
   *
   * \throw scythe_invalid_arg (Level 1)
   * \throw scythe_range_error (Level 1)
   * \throw scythe_precision_error (Level 1)
   */
  inline double
  pbinom(double x, unsigned int n, double p)
  {
      
    SCYTHE_CHECK_10(p < 0 || p > 1, scythe_invalid_arg, "p not in [0,1]");
    double X = std::floor(x);
      
    if (X < 0.0)
      return 0;
    
    if (n <= X)
      return 1;
      
    return pbeta(1 - p, n - X, X + 1);
  }

  SCYTHE_DISTFUN_MATRIX(pbinom, double, SCYTHE_ARGSET(n, p), unsigned int n, double p)

  /* PDFs */
  /*! \brief The binomial density function.
   *
   * Computes the value of the binomial probability density function
   * with \a n trials and \a p probability of success on each trial,
   * at the desired quantile \a x.
   *
   * It is also possible to call this function with a Matrix of
   * doubles as its first argument.  In this case the function will
   * return a Matrix of doubles of the same dimension as \a x,
   * containing the result of evaluating this function at each value
   * in \a x, given the remaining fixed parameters.  By default, the
   * returned Matrix will be concrete and have the same matrix_order
   * as \a x, but you may invoke a generalized version of the function
   * with an explicit template call.
   *
   * \param x The desired quantile.
   * \param n The number of trials.
   * \param p The probability of success on each trial.
   *
   * \see pbinom(double x, unsigned int n, double p)
   * \see rng::rbinom(unsigned int n, double p)
   *
   * \throw scythe_invalid_arg (Level 1)
   * \throw scythe_range_error (Level 1)
   * \throw scythe_precision_error (Level 1)
   */
  inline double
  dbinom(double x, unsigned int n, double p)
  {
    SCYTHE_CHECK_10(p < 0 || p > 1, scythe_invalid_arg, "p not in [0, 1]");
    double X = std::floor(x + 0.5);
    return dbinom_raw(X, n, p, 1 - p);
  }

  SCYTHE_DISTFUN_MATRIX(dbinom, double, SCYTHE_ARGSET(n, p), unsigned int n, double p)

  /**** The Chi Squared Distribution ****/
  
  /* CDFs */
  /*! \brief The \f$\chi^2\f$ distribution function.
   *
   * Computes the value of the \f$\chi^2\f$ cumulative distribution
   * function with \a df degrees of freedom, at the desired quantile
   * \a x.
   *
   * It is also possible to call this function with a Matrix of
   * doubles as its first argument.  In this case the function will
   * return a Matrix of doubles of the same dimension as \a x,
   * containing the result of evaluating this function at each value
   * in \a x, given the remaining fixed parameters.  By default, the
   * returned Matrix will be concrete and have the same matrix_order
   * as \a x, but you may invoke a generalized version of the function
   * with an explicit template call.
   *
   * \param x The desired quantile.
   * \param df The degrees of freedom.

   * \see dchisq(double x, double df)
   * \see rng::rchisq(double df)
   *
   * \throw scythe_invalid_arg (Level 1)
   * \throw scythe_range_error (Level 1)
   * \throw scythe_precision_error (Level 1)
   * \throw scythe_convergence_error (Level 1)
   *
   */
  inline double
  pchisq(double x, double df)
  {
    return pgamma(x, df/2.0, 2.0);
  }

  SCYTHE_DISTFUN_MATRIX(pchisq, double, df, double df)

  /* PDFs */
  /*! \brief The \f$\chi^2\f$ density function.
   *
   * Computes the value of the \f$\chi^2\f$ probability density
   * function with \a df degrees of freedom, at the desired quantile
   * \a x.
   *
   * It is also possible to call this function with a Matrix of
   * doubles as its first argument.  In this case the function will
   * return a Matrix of doubles of the same dimension as \a x,
   * containing the result of evaluating this function at each value
   * in \a x, given the remaining fixed parameters.  By default, the
   * returned Matrix will be concrete and have the same matrix_order
   * as \a x, but you may invoke a generalized version of the function
   * with an explicit template call.
   *
   * \param x The desired quantile.
   * \param df The degrees of freedom.

   * \see pchisq(double x, double df)
   * \see rng::rchisq(double df)
   *
   * \throw scythe_invalid_arg (Level 1)
   * \throw scythe_range_error (Level 1)
   * \throw scythe_precision_error (Level 1)
   * \throw scythe_convergence_error (Level 1)
   *
   */
  inline double
  dchisq(double x, double df)
  {
    return dgamma(x, df / 2.0, 2.0);
  }

  SCYTHE_DISTFUN_MATRIX(dchisq, double, df, double df)

  /**** The Exponential Distribution ****/

  /* CDFs */
  /*! \brief The exponential distribution function.
   *
   * Computes the value of the exponential cumulative distribution
   * function with given \a scale, at the desired quantile
   * \a x.
   *
   * It is also possible to call this function with a Matrix of
   * doubles as its first argument.  In this case the function will
   * return a Matrix of doubles of the same dimension as \a x,
   * containing the result of evaluating this function at each value
   * in \a x, given the remaining fixed parameters.  By default, the
   * returned Matrix will be concrete and have the same matrix_order
   * as \a x, but you may invoke a generalized version of the function
   * with an explicit template call.
   *
   * \param x The desired quantile.
   * \param scale The positive scale of the function.
   *
   * \see dexp(double x, double scale)
   * \see rng::rexp(double scale)
   *
   * \throw scythe_invalid_arg (Level 1)
   */
  inline double
  pexp(double x, double scale)
  {
    SCYTHE_CHECK_10(scale <= 0, scythe_invalid_arg, "scale <= 0");
    
    if (x <= 0)
      return 0;
    
    return (1 - std::exp(-x*scale));
  }

  SCYTHE_DISTFUN_MATRIX(pexp, double, scale, double scale)

  /* PDFs */
  /*! \brief The exponential density function.
   *
   * Computes the value of the exponential probability density
   * function with given \a scale, at the desired quantile
   * \a x.
   *
   * It is also possible to call this function with a Matrix of
   * doubles as its first argument.  In this case the function will
   * return a Matrix of doubles of the same dimension as \a x,
   * containing the result of evaluating this function at each value
   * in \a x, given the remaining fixed parameters.  By default, the
   * returned Matrix will be concrete and have the same matrix_order
   * as \a x, but you may invoke a generalized version of the function
   * with an explicit template call.
   *
   * \param x The desired quantile.
   * \param scale The positive scale of the function.
   *
   * \see pexp(double x, double scale)
   * \see rng::rexp(double scale)
   *
   * \throw scythe_invalid_arg (Level 1)
   */
  inline double
  dexp(double x, double scale)
  {
    SCYTHE_CHECK_10(scale <= 0, scythe_invalid_arg, "scale <= 0");
    
    if (x < 0)
      return 0;
      
    return std::exp(-x * scale) * scale;
  }

  SCYTHE_DISTFUN_MATRIX(dexp, double, scale, double scale)

  /**** The f Distribution ****/

  /* CDFs */
  /*! \brief The F distribution function.
   *
   * Computes the value of the F cumulative distribution function with
   * \a df1 and \a df2 degrees of freedom, at the desired quantile \a
   * x.
   *
   * It is also possible to call this function with a Matrix of
   * doubles as its first argument.  In this case the function will
   * return a Matrix of doubles of the same dimension as \a x,
   * containing the result of evaluating this function at each value
   * in \a x, given the remaining fixed parameters.  By default, the
   * returned Matrix will be concrete and have the same matrix_order
   * as \a x, but you may invoke a generalized version of the function
   * with an explicit template call.
   *
   * \param x The desired quantile.
   * \param df1 The non-negative degrees of freedom for the
   * \f$\chi^2\f$ variate in the nominator of the F statistic.
   * \param df2 The non-negative degrees of freedom for the
   * \f$\chi^2\f$ variate in the denominator of the F statistic.
   *
   *
   * \see df(double x, double df1, double df2)
   * \see rng::rf(double df1, double df2)
   * 
   * \throw scythe_invalid_arg (Level 1)
   * \throw scythe_range_error (Level 1)
   * \throw scythe_precision_error (Level 1)
   * \throw scythe_convergence_error (Level 1)
   */
  inline double
  pf(double x, double df1, double df2)
  {
    SCYTHE_CHECK_10(df1 <= 0 || df2 <= 0, scythe_invalid_arg, 
        "df1 or df2 <= 0");
  
    if (x <= 0)
      return 0;
    
    if (df2 > 4e5)
      return pchisq(x*df1,df1);
    if (df1 > 4e5)
      return 1-pchisq(df2/x,df2);
    
    return (1-pbeta(df2 / (df2 + df1 * x), df2 / 2.0, df1 / 2.0));
  }

  SCYTHE_DISTFUN_MATRIX(pf, double, SCYTHE_ARGSET(df1, df2), double df1, double df2)

  /* PDFs */

  /*! \brief The F density function.
   *
   * Computes the value of the F probability density function with
   * \a df1 and \a df2 degrees of freedom, at the desired quantile \a
   * x.
   *
   * It is also possible to call this function with a Matrix of
   * doubles as its first argument.  In this case the function will
   * return a Matrix of doubles of the same dimension as \a x,
   * containing the result of evaluating this function at each value
   * in \a x, given the remaining fixed parameters.  By default, the
   * returned Matrix will be concrete and have the same matrix_order
   * as \a x, but you may invoke a generalized version of the function
   * with an explicit template call.
   *
   * \param x The desired quantile.
   * \param df1 The non-negative degrees of freedom for the
   * \f$\chi^2\f$ variate in the nominator of the F statistic.
   * \param df2 The non-negative degrees of freedom for the
   * \f$\chi^2\f$ variate in the denominator of the F statistic.
   *
   * \see df(double x, double df1, double df2)
   * \see rng::rf(double df1, double df2)
   * 
   * \throw scythe_invalid_arg (Level 1)
   * \throw scythe_range_error (Level 1)
   * \throw scythe_precision_error (Level 1)
   * \throw scythe_convergence_error (Level 1)
   */
  inline double
  df(double x, double df1, double df2)
  {
    double dens;
    
    SCYTHE_CHECK_10(df1 <= 0 || df2 <= 0, scythe_invalid_arg, 
        "df1 or df2 <= 0");
    
    if (x <= 0)
      return 0;
      
    double f = 1 / (df2 + x * df1);
    double q = df2 * f;
    double p = x * df1 * f;
    
    if (df1 >= 2) {
      f = df1 * q / 2;
      dens = dbinom_raw((df1 - 2) / 2,(df1 + df2 - 2) / 2, p, q);
    } else {
      f = (df1 * df1 * q) /(2 * p * (df1 + df2));
      dens = dbinom_raw(df1 / 2,(df1 + df2)/ 2, p, q);
    }
    
    return f*dens;
  }

  SCYTHE_DISTFUN_MATRIX(df, double, SCYTHE_ARGSET(df1, df2), double df1, double df2)

  /**** The Gamma Distribution ****/

  /* CDFs */
  /*! \brief The gamma distribution function.
   *
   * Computes the value of the gamma cumulative distribution
   * function with given \a shape and \a scale, at the desired quantile
   * \a x.
   *
   * It is also possible to call this function with a Matrix of
   * doubles as its first argument.  In this case the function will
   * return a Matrix of doubles of the same dimension as \a x,
   * containing the result of evaluating this function at each value
   * in \a x, given the remaining fixed parameters.  By default, the
   * returned Matrix will be concrete and have the same matrix_order
   * as \a x, but you may invoke a generalized version of the function
   * with an explicit template call.
   *
   * \param x The desired quantile.
   * \param shape The non-negative shape of the distribution.
   * \param scale The non-negative scale of the distribution.
   *
   * \see dgamma(double x, double shape, double scale)
   * \see rng::rgamma(double shape, double scale)
   * \see gammafn(double x)
   * \see lngammafn(double x)
   *
   * \throw scythe_invalid_arg (Level 1)
   * \throw scythe_range_error (Level 1)
   * \throw scythe_precision_error (Level 1)
   * \throw scythe_convergence_error (Level 1)
   */
  inline double
  pgamma (double x, double shape, double scale)
  {
    const double xbig = 1.0e+8, xlarge = 1.0e+37, 
      alphlimit = 1000.;/* normal approx. for shape > alphlimit */
      
    int lower_tail = 1;

    double pn1, pn2, pn3, pn4, pn5, pn6, arg, a, b, c, an, osum, sum;
    long n;
    int pearson;

    /* check that we have valid values for x and shape */

    SCYTHE_CHECK_10(shape <= 0. || scale <= 0., scythe_invalid_arg,
        "shape or scale <= 0");

    x /= scale;
    
    if (x <= 0.)
      return 0.0;

    /* use a normal approximation if shape > alphlimit */

    if (shape > alphlimit) {
      pn1 = std::sqrt(shape) * 3. * (std::pow(x/shape, 1./3.) + 1.
            / (9. * shape) - 1.);
      return pnorm(pn1, 0., 1.);
    }

    /* if x is extremely large __compared to shape__ then return 1 */

    if (x > xbig * shape)
      return 1.0;

    if (x <= 1. || x < shape) {
      pearson = 1;/* use pearson's series expansion. */
      arg = shape * std::log(x) - x - lngammafn(shape + 1.);
      c = 1.;
      sum = 1.;
      a = shape;
      do {
        a += 1.;
        c *= x / a;
        sum += c;
      } while (c > DBL_EPSILON);
      arg += std::log(sum);
    }
    else { /* x >= max( 1, shape) */
      pearson = 0;/* use a continued fraction expansion */
      arg = shape * std::log(x) - x - lngammafn(shape);
      a = 1. - shape;
      b = a + x + 1.;
      pn1 = 1.;
      pn2 = x;
      pn3 = x + 1.;
      pn4 = x * b;
      sum = pn3 / pn4;
      for (n = 1; ; n++) {
        a += 1.;/* =   n+1 -shape */
        b += 2.;/* = 2(n+1)-shape+x */
        an = a * n;
        pn5 = b * pn3 - an * pn1;
        pn6 = b * pn4 - an * pn2;
        if (std::fabs(pn6) > 0.) {
          osum = sum;
          sum = pn5 / pn6;
          if (std::fabs(osum - sum) <= DBL_EPSILON * std::min(1., sum))
            break;
        }
        pn1 = pn3;
        pn2 = pn4;
        pn3 = pn5;
        pn4 = pn6;
        if (std::fabs(pn5) >= xlarge) {
          /* re-scale terms in continued fraction if they are large */
          pn1 /= xlarge;
          pn2 /= xlarge;
          pn3 /= xlarge;
          pn4 /= xlarge;
        }
      }
      arg += std::log(sum);
    }

    lower_tail = (lower_tail == pearson);

    sum = std::exp(arg);

    return (lower_tail) ? sum : 1 - sum;
  }

  SCYTHE_DISTFUN_MATRIX(pgamma, double, SCYTHE_ARGSET(shape, scale), double shape, double scale)

  /* PDFs */
  /*! \brief The gamma density function.
   *
   * Computes the value of the gamma probability density
   * function with given \a shape and \a scale, at the desired quantile
   * \a x.
   *
   * It is also possible to call this function with a Matrix of
   * doubles as its first argument.  In this case the function will
   * return a Matrix of doubles of the same dimension as \a x,
   * containing the result of evaluating this function at each value
   * in \a x, given the remaining fixed parameters.  By default, the
   * returned Matrix will be concrete and have the same matrix_order
   * as \a x, but you may invoke a generalized version of the function
   * with an explicit template call.
   *
   * \param x The desired quantile.
   * \param shape The non-negative shape of the distribution.
   * \param scale The non-negative scale of the distribution.
   *
   * \see pgamma(double x, double shape, double scale)
   * \see rng::rgamma(double shape, double scale)
   * \see gammafn(double x)
   * \see lngammafn(double x)
   *
   * \throw scythe_invalid_arg (Level 1)
   * \throw scythe_range_error (Level 1)
   * \throw scythe_precision_error (Level 1)
   * \throw scythe_convergence_error (Level 1)
   */
  inline double
  dgamma(double x, double shape, double scale)
  {
    SCYTHE_CHECK_10(shape <= 0 || scale <= 0,scythe_invalid_arg,
        "shape or scale <= 0");

    if (x < 0)
      return 0.0;
    
    if (x == 0) {
      SCYTHE_CHECK_10(shape < 1,scythe_invalid_arg, 
          "x == 0 and shape < 1");
      
      if (shape > 1)
        return 0.0;
      
      return 1 / scale;
    }
    
    if (shape < 1) { 
      double pr = dpois_raw(shape, x/scale);
      return pr * shape / x;
    }
    
    /* else  shape >= 1 */
    double pr = dpois_raw(shape - 1, x / scale);
    return pr / scale;
  }

  SCYTHE_DISTFUN_MATRIX(dgamma, double, SCYTHE_ARGSET(shape, scale), double shape, double scale)

  /**** The Logistic Distribution ****/

  /* CDFs */
  /*! \brief The logistic distribution function.
   *
   * Computes the value of the logistic cumulative distribution
   * function with given \a location and \a scale, at the desired
   * quantile \a x.
   *
   * It is also possible to call this function with a Matrix of
   * doubles as its first argument.  In this case the function will
   * return a Matrix of doubles of the same dimension as \a x,
   * containing the result of evaluating this function at each value
   * in \a x, given the remaining fixed parameters.  By default, the
   * returned Matrix will be concrete and have the same matrix_order
   * as \a x, but you may invoke a generalized version of the function
   * with an explicit template call.
   *
   * \param x The desired quantile.
   * \param location The location of the distribution.
   * \param scale The positive scale of the distribution.
   *
   * \see dlogis(double x, double location, double scale)
   * \see rng::rlogis(double location, double scale)
   * 
   * \throw scythe_invalid_arg (Level 1)
   */
  inline double
  plogis (double x, double location, double scale)
  {
    SCYTHE_CHECK_10(scale <= 0.0, scythe_invalid_arg, "scale <= 0");
    
    double X = (x-location) / scale;
      
    X = std::exp(-X);
      
    return 1 / (1+X);
  }

  SCYTHE_DISTFUN_MATRIX(plogis, double, SCYTHE_ARGSET(location, scale), double location, double scale)

  /* PDFs */
  /*! \brief The logistic density function.
   *
   * Computes the value of the logistic probability density
   * function with given \a location and \a scale, at the desired
   * quantile \a x.
   *
   * It is also possible to call this function with a Matrix of
   * doubles as its first argument.  In this case the function will
   * return a Matrix of doubles of the same dimension as \a x,
   * containing the result of evaluating this function at each value
   * in \a x, given the remaining fixed parameters.  By default, the
   * returned Matrix will be concrete and have the same matrix_order
   * as \a x, but you may invoke a generalized version of the function
   * with an explicit template call.
   *
   * \param x The desired quantile.
   * \param location The location of the distribution.
   * \param scale The positive scale of the distribution.
   *
   * \see plogis(double x, double location, double scale)
   * \see rng::rlogis(double location, double scale)
   * 
   * \throw scythe_invalid_arg (Level 1)
   */
  inline double
  dlogis(double x, double location, double scale)
  {
    SCYTHE_CHECK_10(scale <= 0.0, scythe_invalid_arg, "scale <= 0");
    
    double X = (x - location) / scale;
    double e = std::exp(-X);
    double f = 1.0 + e;
      
    return e / (scale * f * f);
  }

  SCYTHE_DISTFUN_MATRIX(dlogis, double, SCYTHE_ARGSET(location, scale), double location, double scale)

  /**** The Log Normal Distribution ****/

  /* CDFs */
  /*! \brief The log-normal distribution function.
   *
   * Computes the value of the log-normal cumulative distribution
   * function with mean \a logmean and standard
   * deviation \a logsd, at the desired quantile \a x.
   *
   * It is also possible to call this function with a Matrix of
   * doubles as its first argument.  In this case the function will
   * return a Matrix of doubles of the same dimension as \a x,
   * containing the result of evaluating this function at each value
   * in \a x, given the remaining fixed parameters.  By default, the
   * returned Matrix will be concrete and have the same matrix_order
   * as \a x, but you may invoke a generalized version of the function
   * with an explicit template call.
   *
   * \param x The desired quantile.
   * \param logmean The mean of the distribution.
   * \param logsd The positive standard deviation of the distribution.
   *
   * \see dlnorm(double x, double logmean, double logsd)
   * \see rng::rlnorm(double logmean, double logsd)
   * \see pnorm(double x, double logmean, double logsd)
   *
   * \throw scythe_invalid_arg (Level 1)
   * \throw scythe_convergence_error (Level 1)
   */
  inline double
  plnorm (double x, double logmean, double logsd)
  {
    SCYTHE_CHECK_10(logsd <= 0, scythe_invalid_arg, "logsd <= 0");
    
    if (x > 0)
      return pnorm(std::log(x), logmean, logsd);
    
    return 0;
  }

  SCYTHE_DISTFUN_MATRIX(plnorm, double, SCYTHE_ARGSET(logmean, logsd), double logmean, double logsd)

  /* PDFs */
  /*! \brief The log-normal density function.
   *
   * Computes the value of the log-normal probability density
   * function with mean \a logmean and standard
   * deviation \a logsd, at the desired quantile \a x.
   *
   * It is also possible to call this function with a Matrix of
   * doubles as its first argument.  In this case the function will
   * return a Matrix of doubles of the same dimension as \a x,
   * containing the result of evaluating this function at each value
   * in \a x, given the remaining fixed parameters.  By default, the
   * returned Matrix will be concrete and have the same matrix_order
   * as \a x, but you may invoke a generalized version of the function
   * with an explicit template call.
   *
   * \param x The desired quantile.
   * \param logmean The mean of the distribution.
   * \param logsd The positive standard deviation of the distribution.
   *
   * \see plnorm(double x, double logmean, double logsd)
   * \see rng::rlnorm(double logmean, double logsd)
   * \see dnorm(double x, double logmean, double logsd)
   *
   * \throw scythe_invalid_arg (Level 1)
   */
  inline double
  dlnorm(double x, double logmean, double logsd)
  {
    SCYTHE_CHECK_10(logsd <= 0, scythe_invalid_arg, "logsd <= 0");
    
    if (x == 0)
      return 0;
    
    double y = (std::log(x) - logmean) / logsd;
    
    return (1 / (std::sqrt(2 * M_PI))) * std::exp(-0.5 * y * y) / (x * logsd);
  }

  SCYTHE_DISTFUN_MATRIX(dlnorm, double, SCYTHE_ARGSET(logmean, logsd), double logmean, double logsd)

  /**** The Negative Binomial Distribution ****/

  /* CDFs */
  /*! \brief The negative binomial distribution function.
   *
   * Computes the value of the negative binomial cumulative distribution
   * function with \a n target number of successful trials and \a p
   * probability of success on each trial, at the desired quantile \a
   * x.
   *
   * It is also possible to call this function with a Matrix of
   * doubles as its first argument.  In this case the function will
   * return a Matrix of doubles of the same dimension as \a x,
   * containing the result of evaluating this function at each value
   * in \a x, given the remaining fixed parameters.  By default, the
   * returned Matrix will be concrete and have the same matrix_order
   * as \a x, but you may invoke a generalized version of the function
   * with an explicit template call.
   *
   * \param x The desired non-negative, integer, quantile.
   * \param n The positive target number of successful trials
   * (dispersion parameter).
   * \param p The probability of success on each trial.
   *
   * \see dnbinom(unsigned int x, double n, double p)
   * \see rng::rnbinom(double n, double p)
   *
   * \throw scythe_invalid_arg (Level 1)
   * \throw scythe_range_error (Level 1)
   * \throw scythe_precision_error (Level 1)
   */
  inline double
  pnbinom(unsigned int x, double n, double p)
  {
    SCYTHE_CHECK_10(n == 0 || p <= 0 || p >= 1, scythe_invalid_arg,
        "n == 0 or p not in (0,1)");
    
    return pbeta(p, n, x + 1);
  }

  SCYTHE_DISTFUN_MATRIX(pnbinom, unsigned int, SCYTHE_ARGSET(n, p), double n, double p)

  /* PDFs */
  /*! \brief The negative binomial density function.
   *
   * Computes the value of the negative binomial probability density
   * function with \a n target number of successful trials and \a p
   * probability of success on each trial, at the desired quantile \a
   * x.
   *
   * It is also possible to call this function with a Matrix of
   * doubles as its first argument.  In this case the function will
   * return a Matrix of doubles of the same dimension as \a x,
   * containing the result of evaluating this function at each value
   * in \a x, given the remaining fixed parameters.  By default, the
   * returned Matrix will be concrete and have the same matrix_order
   * as \a x, but you may invoke a generalized version of the function
   * with an explicit template call.
   *
   * \param x The desired non-negative, integer, quantile.
   * \param n The positive target number of successful trials
   * (dispersion parameter).
   * \param p The probability of success on each trial.
   *
   * \see dnbinom(unsigned int x, double n, double p)
   * \see rng::rnbinom(double n, double p)
   *
   * \throw scythe_invalid_arg (Level 1)
   * \throw scythe_range_error (Level 1)
   * \throw scythe_precision_error (Level 1)
   */
  inline double
  dnbinom(unsigned int x, double n, double p)
  {
    SCYTHE_CHECK_10(n == 0 || p <= 0 || p >= 1, scythe_invalid_arg,
        "n == 0 or p not in (0,1)");
    
    double prob = dbinom_raw(n, x + n, p, 1 - p);
    double P = (double) n / (n + x);
    
    return P * prob;
  }

  SCYTHE_DISTFUN_MATRIX(dnbinom, unsigned int, SCYTHE_ARGSET(n, p), double n, double p)

  /**** The Normal Distribution ****/
  
  /* CDFs */
  /*! \brief The normal distribution function.
   *
   * Computes the value of the normal cumulative distribution
   * function with given \a mean and standard deviation \a sd, at the
   * desired quantile \a x.
   *
   * It is also possible to call this function with a Matrix of
   * doubles as its first argument.  In this case the function will
   * return a Matrix of doubles of the same dimension as \a x,
   * containing the result of evaluating this function at each value
   * in \a x, given the remaining fixed parameters.  By default, the
   * returned Matrix will be concrete and have the same matrix_order
   * as \a x, but you may invoke a generalized version of the function
   * with an explicit template call.
   *
   * \param x The desired quantile.
   * \param mean The mean of the distribution.
   * \param sd The positive standard deviation of the distribution.
   *
   * \see dnorm(double x, double mean, double sd)
   * \see rng::rnorm(double mean, double sd)
   *
   * \throw scythe_invalid_arg (Level 1)
   * \throw scythe_convergence_error (Level 1)
   */
  inline double
  pnorm (double x, double mean, double sd)
  
  {
    SCYTHE_CHECK_10(sd <= 0, scythe_invalid_arg,
        "negative standard deviation");

    return pnorm1((x - mean) / sd, true, false);
  }

  SCYTHE_DISTFUN_MATRIX(pnorm, double, SCYTHE_ARGSET(mean, sd), double mean, double sd)
  

  /* PDFs */
  /*! \brief The normal density function.
   *
   * Computes the value of the normal probability density
   * function with given \a mean and standard deviation \a sd, at the
   * desired quantile \a x.
   *
   * It is also possible to call this function with a Matrix of
   * doubles as its first argument.  In this case the function will
   * return a Matrix of doubles of the same dimension as \a x,
   * containing the result of evaluating this function at each value
   * in \a x, given the remaining fixed parameters.  By default, the
   * returned Matrix will be concrete and have the same matrix_order
   * as \a x, but you may invoke a generalized version of the function
   * with an explicit template call.
   *
   * \param x The desired quantile.
   * \param mean The mean of the distribution.
   * \param sd The positive standard deviation of the distribution.
   *
   * \see pnorm(double x, double mean, double sd)
   * \see rng::rnorm(double mean, double sd)
   *
   * \throw scythe_invalid_arg (Level 1)
   */
  inline double
  dnorm(double x, double mean, double sd)
  {
    SCYTHE_CHECK_10(sd <= 0, scythe_invalid_arg,
        "negative standard deviation");
    
    double X = (x - mean) / sd;
    
    return (M_1_SQRT_2PI * std::exp(-0.5 * X * X) / sd);
  }

  SCYTHE_DISTFUN_MATRIX(dnorm, double, SCYTHE_ARGSET(mean, sd), double mean, double sd)
 

  /* Return the natural log of the normal PDF */
  /*! \brief The natural log of normal density function.
   *
   * Computes the value of the natural log of the normal probability
   * density function with given \a mean and standard deviation \a sd,
   * at the desired quantile \a x.
   *
   * It is also possible to call this function with a Matrix of
   * doubles as its first argument.  In this case the function will
   * return a Matrix of doubles of the same dimension as \a x,
   * containing the result of evaluating this function at each value
   * in \a x, given the remaining fixed parameters.  By default, the
   * returned Matrix will be concrete and have the same matrix_order
   * as \a x, but you may invoke a generalized version of the function
   * with an explicit template call.
   *
   * \param x The desired quantile.
   * \param mean The mean of the distribution.
   * \param sd The positive standard deviation of the distribution.
   *
   * \see dnorm(double x, double mean, double sd)
   * \see pnorm(double x, double mean, double sd)
   * \see rng::rnorm(double mean, double sd)
   *
   * \throw scythe_invalid_arg (Level 1)
   */
  inline double
  lndnorm (double x, double mean, double sd)
  {
    SCYTHE_CHECK_10(sd <= 0, scythe_invalid_arg,
        "negative standard deviation");
    
    double X = (x - mean) / sd;
    
    return -(M_LN_SQRT_2PI  +  0.5 * X * X + std::log(sd));
  }

  SCYTHE_DISTFUN_MATRIX(lndnorm, double, SCYTHE_ARGSET(mean, sd), double mean, double sd)

  /* Quantile functions */
  /*! \brief The standard normal quantile function.
   *
   * Computes the value of the standard normal quantile function
   * at the desired probability \a in_p.
   *
   * It is also possible to call this function with a Matrix of
   * doubles as its first argument.  In this case the function will
   * return a Matrix of doubles of the same dimension as \a x,
   * containing the result of evaluating this function at each value
   * in \a x, given the remaining fixed parameters.  By default, the
   * returned Matrix will be concrete and have the same matrix_order
   * as \a x, but you may invoke a generalized version of the function
   * with an explicit template call.
   *
   * \param in_p The desired probability.
   *
   * \see pnorm(double x, double mean, double sd)
   * \see dnorm(double x, double mean, double sd)
   * \see rng::rnorm(double mean, double sd)
   *
   * \throw scythe_invalid_arg (Level 1)
   */
  inline double
  qnorm1 (double in_p)
  {
    double p0 = -0.322232431088;
    double q0 = 0.0993484626060;
    double p1 = -1.0;
    double q1 = 0.588581570495;
    double p2 = -0.342242088547;
    double q2 = 0.531103462366;
    double p3 = -0.0204231210245;
    double q3 = 0.103537752850;
    double p4 = -0.453642210148e-4;
    double q4 = 0.38560700634e-2;
    double xp = 0.0;
    double p = in_p;
      
    if (p > 0.5)
      p = 1 - p;
        
    SCYTHE_CHECK_10(p < 10e-20, scythe_range_error,
        "p outside accuracy limit");
      
    if (p == 0.5)
      return xp;
      
    double y = std::sqrt (std::log (1.0 / std::pow (p, 2)));
    xp = y + ((((y * p4 + p3) * y + p2) * y + p1) * y + p0) /
      ((((y * q4 + q3) * y + q2) * y + q1) * y + q0);
      
    if (in_p < 0.5)
      xp = -1 * xp;
    
    return xp;
  }

  SCYTHE_DISTFUN_MATRIX(qnorm1, double, in_p, double in_p)

  /**** The Poisson Distribution ****/

  /* CDFs */
  /*! \brief The Poisson distribution function.
   *
   * Computes the value of the Poisson cumulative distribution
   * function with expected number of occurrences \a lambda, at the
   * desired quantile \a x.
   *
   * It is also possible to call this function with a Matrix of
   * doubles as its first argument.  In this case the function will
   * return a Matrix of doubles of the same dimension as \a x,
   * containing the result of evaluating this function at each value
   * in \a x, given the remaining fixed parameters.  By default, the
   * returned Matrix will be concrete and have the same matrix_order
   * as \a x, but you may invoke a generalized version of the function
   * with an explicit template call.
   *
   * \param x The desired integer quantile.
   * \param lambda The expected positive number of occurrences.
   *
   * \see dpois(unsigned int x, double lambda)
   * \see rng::rpois(double lambda)
   *
   * \throws scythe_invalid_arg (Level 1)
   * \throw scythe_range_error (Level 1)
   * \throw scythe_precision_error (Level 1)
   * \throw scythe_convergence_error (Level 1)
   */
  inline double
  ppois(unsigned int x, double lambda)
  {
    SCYTHE_CHECK_10(lambda<=0.0, scythe_invalid_arg, "lambda <= 0");
    
    if (lambda == 1)
      return 1;
    
    return 1 - pgamma(lambda, x + 1, 1.0);
  }

  SCYTHE_DISTFUN_MATRIX(ppois, unsigned int, lambda, double lambda)

  /* PDFs */
  /*! \brief The Poisson density function.
   *
   * Computes the value of the Poisson probability density
   * function with expected number of occurrences \a lambda, at the
   * desired quantile \a x.
   *
   * It is also possible to call this function with a Matrix of
   * doubles as its first argument.  In this case the function will
   * return a Matrix of doubles of the same dimension as \a x,
   * containing the result of evaluating this function at each value
   * in \a x, given the remaining fixed parameters.  By default, the
   * returned Matrix will be concrete and have the same matrix_order
   * as \a x, but you may invoke a generalized version of the function
   * with an explicit template call.
   *
   * \param x The desired integer quantile.
   * \param lambda The expected positive number of occurrences.
   *
   * \see ppois(unsigned int x, double lambda)
   * \see rng::rpois(double lambda)
   *
   * \throws scythe_invalid_arg (Level 1)
   */
  inline double
  dpois(unsigned int x, double lambda)
  {
    SCYTHE_CHECK_10(lambda<=0.0, scythe_invalid_arg, "lambda <= 0");
    
    // compute log(x!)
    double xx = x+1;
    double cof[6] = {
      76.18009172947146, -86.50532032941677,
      24.01409824083091, -1.231739572450155,
      0.1208650973866179e-2, -0.5395239384953e-5
    };
    double y = xx;
    double tmp = xx + 5.5 - (xx + 0.5) * std::log(xx + 5.5);
    double ser = 1.000000000190015;
    for (int j = 0; j <= 5; j++) {
      ser += (cof[j] / ++y);
    }
    double lnfactx = std::log(2.5066282746310005 * ser / xx) - tmp;
      
    return (std::exp( -1*lnfactx + x * std::log(lambda) - lambda));
  }

  SCYTHE_DISTFUN_MATRIX(dpois, unsigned int, lambda, double lambda)

  /**** The t Distribution ****/

  /* CDFs */
  /*! \brief The Student t distribution function.
   *
   * Computes the value of the Student t cumulative distribution
   * function with \a n degrees of freedom, at the desired quantile
   * \a x.
   *
   * It is also possible to call this function with a Matrix of
   * doubles as its first argument.  In this case the function will
   * return a Matrix of doubles of the same dimension as \a x,
   * containing the result of evaluating this function at each value
   * in \a x, given the remaining fixed parameters.  By default, the
   * returned Matrix will be concrete and have the same matrix_order
   * as \a x, but you may invoke a generalized version of the function
   * with an explicit template call.
   *
   * \param x The desired quantile.
   * \param n The positive degrees of freedom of the distribution.
   *
   * \see dt(double x, bool b1, bool b2)
   * \see rng::rt1(double mu, double sigma2, double nu)
   * 
   * \throw scythe_invalid_arg (Level 1)
   * \throw scythe_convergence_error (Level 1)
   * \throw scythe_range_error (Level 1)
   * \throw scythe_precision_error (Level 1)
   */
  inline double
  pt(double x, double n)
  {
    double val;
    
    SCYTHE_CHECK_10(n <= 0, scythe_invalid_arg, "n <= 0");
    
    if (n > 4e5) {
      val = 1/(4*n);
      return pnorm1(x * (1 - val) / ::sqrt(1 + x * x * 2. * val), 
          true, false);
    }
    
    val = pbeta(n / (n + x * x), n / 2.0, 0.5);
    
    val /= 2;
    
    if (x <= 0)
      return val;
    else
      return 1 - val;
  }

  SCYTHE_DISTFUN_MATRIX(pt, double, n, double n)
  
  /* PDFs */
  /*! \brief The Student t distribution function.
   *
   * Computes the value of the Student t cumulative distribution
   * function with \a n degrees of freedom, at the desired quantile
   * \a x.
   *
   * It is also possible to call this function with a Matrix of
   * doubles as its first argument.  In this case the function will
   * return a Matrix of doubles of the same dimension as \a x,
   * containing the result of evaluating this function at each value
   * in \a x, given the remaining fixed parameters.  By default, the
   * returned Matrix will be concrete and have the same matrix_order
   * as \a x, but you may invoke a generalized version of the function
   * with an explicit template call.
   *
   * \param x The desired quantile.
   * \param n The positive degrees of freedom of the distribution.
   *
   * \see pt(double x, bool b1, bool b2)
   * \see rng::rt1(double mu, double sigma2, double nu)
   * 
   * \throw scythe_invalid_arg (Level 1)
   * \throw scythe_range_error (Level 1)
   * \throw scythe_precision_error (Level 1)
   */
  inline double
  dt(double x, double n)
  {
    double u;

    SCYTHE_CHECK_10(n <= 0, scythe_invalid_arg, "n <= 0");
    
    double t = -bd0(n/2., (n + 1) / 2.)
      + stirlerr((n + 1) / 2.)
      - stirlerr(n / 2.);
    if(x*x > 0.2*n)
      u = std::log(1+x*x/n)*n/2;
    else
      u = -bd0(n/2., (n+x*x)/2.) + x*x/2;
    
    return std::exp(t-u)/std::sqrt(2*M_PI*(1+x*x/n));
  }

  SCYTHE_DISTFUN_MATRIX(dt, double, n, double n)
  
  /* Returns the univariate Student-t density evaluated at x 
   * with mean mu, scale sigma^2, and nu degrees of freedom.  
   *
   * TODO:  Do we want a pt for this distribution?
   */

  /*! \brief The univariate Student t density function.
   *
   * Computes the value of the univariate Student t probability
   * density function with mean \a mu, variance \a sigma2,
   * and degrees of freedom \a nu, at the desired quantile \a x.
   *
   * It is also possible to call this function with a Matrix of
   * doubles as its first argument.  In this case the function will
   * return a Matrix of doubles of the same dimension as \a x,
   * containing the result of evaluating this function at each value
   * in \a x, given the remaining fixed parameters.  By default, the
   * returned Matrix will be concrete and have the same matrix_order
   * as \a x, but you may invoke a generalized version of the function
   * with an explicit template call.
   *
   * \param x The desired quantile.
   * \param mu The mean of the distribution.
   * \param sigma2 The variance of the distribution.
   * \param nu The degrees of freedom of the distribution.
   *
   * \see rng::rt1(double mu, double sigma2, double nu)
   * \see dt(double x, bool b1, bool b2)
   * \see pt(double x, bool b1, bool b2)
   *
   * \throw scythe_invalid_arg (Level 1)
   * \throw scythe_range_error (Level 1)
   * \throw scythe_precision_error (Level 1)
   */
  inline double
  dt1(double x, double mu, double sigma2, double nu)
  {
    double logdens =   lngammafn((nu + 1.0) /2.0)
      - std::log(std::sqrt(nu * M_PI))
      - lngammafn(nu / 2.0) - std::log(std::sqrt(sigma2))
      - (nu + 1.0) / 2.0 * std::log(1.0 + (std::pow((x - mu), 2.0))
            / (nu * sigma2));
    
    return(std::exp(logdens));
  }

  SCYTHE_DISTFUN_MATRIX(dt1, double, SCYTHE_ARGSET(mu, sigma2, nu), double mu, double sigma2, double nu)

  /* Returns the natural log of the univariate Student-t density 
   * evaluated at x with mean mu, scale sigma^2, and nu 
   * degrees of freedom
   */
   
  /*! \brief The natural log of the univariate Student t density
   * function.
   *
   * Computes the value of the natural log of the univariate Student t
   * probability density function with mean \a mu, variance \a sigma2,
   * and degrees of freedom \a nu, at the desired quantile \a x.
   *
   * It is also possible to call this function with a Matrix of
   * doubles as its first argument.  In this case the function will
   * return a Matrix of doubles of the same dimension as \a x,
   * containing the result of evaluating this function at each value
   * in \a x, given the remaining fixed parameters.  By default, the
   * returned Matrix will be concrete and have the same matrix_order
   * as \a x, but you may invoke a generalized version of the function
   * with an explicit template call.
   *
   * \param x The desired quantile.
   * \param mu The mean of the distribution.
   * \param sigma2 The variance of the distribution.
   * \param nu The degrees of freedom of the distribution.
   *
   * \see rng::rt1(double mu, double sigma2, double nu)
   * \see dt(double x, bool b1, bool b2)
   * \see pt(double x, bool b1, bool b2)
   *
   * \throw scythe_invalid_arg (Level 1)
   * \throw scythe_range_error (Level 1)
   * \throw scythe_precision_error (Level 1)
   */
  inline double 
  lndt1(double x, double mu, double sigma2, double nu)
  {
    double logdens = lngammafn((nu+1.0)/2.0)
      - std::log(std::sqrt(nu*M_PI))
      - lngammafn(nu/2.0) - std::log(std::sqrt(sigma2))
      - (nu+1.0)/2.0 * std::log(1.0 + (std::pow((x-mu),2.0))
        /(nu * sigma2));
    
    return(logdens);
  }

  SCYTHE_DISTFUN_MATRIX(lndt1, double, SCYTHE_ARGSET(mu, sigma2, nu), double mu, double sigma2, double nu)

  /**** The Uniform Distribution ****/

  /* CDFs */
  /*! \brief The uniform distribution function.
   *
   * Computes the value of the uniform cumulative distribution
   * function evaluated on the interval [\a a, \a b], at the desired
   * quantile \a x.
   *
   * It is also possible to call this function with a Matrix of
   * doubles as its first argument.  In this case the function will
   * return a Matrix of doubles of the same dimension as \a x,
   * containing the result of evaluating this function at each value
   * in \a x, given the remaining fixed parameters.  By default, the
   * returned Matrix will be concrete and have the same matrix_order
   * as \a x, but you may invoke a generalized version of the function
   * with an explicit template call.
   *
   * \param x The desired quantile x.
   * \param a The lower end-point of the distribution.
   * \param b The upper end-point of the distribution.
   *
   * \see dunif(double x, double a, double b)
   * \see rng::runif()
   *
   * \throw scythe_invalid_arg (Level 1)
   */
  inline double
  punif(double x, double a, double b)
  {
    SCYTHE_CHECK_10(b <= a, scythe_invalid_arg, "b <= a");
      
    if (x <= a)
      return 0.0;
        
    if (x >= b)
      return 1.0;
      
    return (x - a) / (b - a);
  }

  SCYTHE_DISTFUN_MATRIX(punif, double, SCYTHE_ARGSET(a, b), double a, double b)

  /* PDFs */
  /*! \brief The uniform density function.
   *
   * Computes the value of the uniform probability density
   * function evaluated on the interval [\a a, \a b], at the desired
   * quantile \a x.
   *
   * It is also possible to call this function with a Matrix of
   * doubles as its first argument.  In this case the function will
   * return a Matrix of doubles of the same dimension as \a x,
   * containing the result of evaluating this function at each value
   * in \a x, given the remaining fixed parameters.  By default, the
   * returned Matrix will be concrete and have the same matrix_order
   * as \a x, but you may invoke a generalized version of the function
   * with an explicit template call.
   *
   * \param x The desired quantile x.
   * \param a The lower end-point of the distribution.
   * \param b The upper end-point of the distribution.
   *
   * \see punif(double x, double a, double b)
   * \see rng::runif()
   *
   * \throw scythe_invalid_arg (Level 1)
   */
  inline double
  dunif(double x, double a, double b)
  {
    SCYTHE_CHECK_10(b <= a, scythe_invalid_arg, "b <= a");
    
    if (a <= x && x <= b)
      return 1.0 / (b - a);
    
    return 0.0;
  }

  SCYTHE_DISTFUN_MATRIX(dunif, double, SCYTHE_ARGSET(a, b), double a, double b)

  /**** The Weibull Distribution ****/

  /* CDFs */
  /*! \brief The Weibull distribution function.
   *
   * Computes the value of the Weibull cumulative distribution
   * function with given \a shape and \a scale, at the desired
   * quantile \a x.
   *
   * It is also possible to call this function with a Matrix of
   * doubles as its first argument.  In this case the function will
   * return a Matrix of doubles of the same dimension as \a x,
   * containing the result of evaluating this function at each value
   * in \a x, given the remaining fixed parameters.  By default, the
   * returned Matrix will be concrete and have the same matrix_order
   * as \a x, but you may invoke a generalized version of the function
   * with an explicit template call.
   *
   * \param x The desired quantile.
   * \param shape The positive shape of the distribution.
   * \param scale The positive scale of the distribution.
   *
   * \see dweibull(double x, double shape, double scale)
   * \see rng::rweibull(double shape, double scale)
   *
   * \throw scythe_invalid_arg (Level 1)
   */
  inline double
  pweibull(double x, double shape, double scale)
  {
    SCYTHE_CHECK_10(shape <= 0 || scale <= 0, scythe_invalid_arg,
        "shape or scale <= 0");
    
    if (x <= 0)
      return 0.0;
    
    return 1 - std::exp(-std::pow(x / scale, shape));
  }

  SCYTHE_DISTFUN_MATRIX(pweibull, double, SCYTHE_ARGSET(shape, scale), double shape, double scale)

  /* PDFs */
  /*! \brief The Weibull density function.
   *
   * Computes the value of the Weibull probability density
   * function with given \a shape and \a scale, at the desired
   * quantile \a x.
   *
   * It is also possible to call this function with a Matrix of
   * doubles as its first argument.  In this case the function will
   * return a Matrix of doubles of the same dimension as \a x,
   * containing the result of evaluating this function at each value
   * in \a x, given the remaining fixed parameters.  By default, the
   * returned Matrix will be concrete and have the same matrix_order
   * as \a x, but you may invoke a generalized version of the function
   * with an explicit template call.
   *
   * \param x The desired quantile.
   * \param shape The positive shape of the distribution.
   * \param scale The positive scale of the distribution.
   *
   * \see pweibull(double x, double shape, double scale)
   * \see rng::rweibull(double shape, double scale)
   *
   * \throw scythe_invalid_arg (Level 1)
   */
  inline double
  dweibull(double x, double shape, double scale)
  {
    SCYTHE_CHECK_10(shape <= 0 || scale <= 0, scythe_invalid_arg,
        "shape or scale <= 0");

    if (x < 0)
      return 0.;
      
    double tmp1 = std::pow(x / scale, shape - 1);
    double tmp2 = tmp1*(x / scale);
      
    return shape * tmp1 * std::exp(-tmp2) / scale;
  }

  SCYTHE_DISTFUN_MATRIX(dweibull, double, SCYTHE_ARGSET(shape, scale), double shape, double scale)

  /* Multivariate Normal */

  // TODO: distribution function.  Plain old (non-logged) dmvnorm.

  /*! \brief The natural log of the multivariate normal density
   * function.
   *
   * Computes the value of the natural log of the multivariate normal
   * probability density function with vector of mean \a mu and
   * variance-covariance matrix \a Sigma, at the vector of desired
   * quantiles \a x.
   *
   * \param x The vector of desired quantiles.
   * \param mu The vector of means.
   * \param Sigma The variance-covariance matrix.
   *
   * \see rng:rmvnorm(const Matrix<double, PO1, PS1>& mu, const Matrix<double, PO2, PS2>& sigma)
   *
   * \throw scythe_dimension_error (Level 1)
   * \throw scythe_conformation_error (Level 1)
   * \throw scythe_null_error (Level 1)
   */
  template <matrix_order O1, matrix_style S1,
            matrix_order O2, matrix_style S2,
            matrix_order O3, matrix_style S3>
  double lndmvn (const Matrix<double, O1, S1>& x,
                 const Matrix<double, O2, S2>& mu,
                 const Matrix<double, O3, S3>& Sigma)
  {
    SCYTHE_CHECK_10(! x.isColVector(), scythe_dimension_error,
        "x is not a column vector");
    SCYTHE_CHECK_10(! mu.isColVector(), scythe_dimension_error,
        "mu is not a column vector");
    SCYTHE_CHECK_10(! Sigma.isSquare(), scythe_dimension_error,
        "Sigma is not square");
    SCYTHE_CHECK_10(mu.rows()!=Sigma.rows() || x.rows()!=Sigma.rows(), 
                    scythe_conformation_error,
                    "mu, x and Sigma have mismatched row lengths")
    int k = (int) mu.rows();
    return ( (-k/2.0)*std::log(2*M_PI) -0.5 * std::log(det(Sigma)) 
       -0.5 * (t(x - mu)) * invpd(Sigma) * (x-mu) )[0];
  }

} // end namespace scythe


#endif /* SCYTHE_DISTRIBUTIONS_H */