libRmath.js
This R statistical nmath
re-created in typescript/javascript.
This is a manual re-write, "emscripten" was not used.
Summary
libRmath.js port contains all functions implemented in R nmath
counterpart:
- probability and quantile functions related to 21 distributions.
- functions to work with
Special functions in mathematics
(Bessel
,Gamma
,Beta
). - 7 uniform PRNG's. (same output pseudo-random sequence in R for the same initial seeding).
- 6 normally distributed PRNG's. (same output sequence in R for te same initial seeding).
- Function vector (array) arguments follow the R recycling rule.
With this library it becomes trivial to implement hypothesis testing in javascript, calculating p-values and (1 - α) confidence intervals. (ANOVA
uses the F-distribution. Tukey HSD uses ptukey
function, etc, etc).
All functions in libRmath.so
has been re-written to Javascript
(Typescript
).
Use the library with either vanilla Javascript
or Typescript
.
Type definition files are included in the npm package.
Node and Web
The library is an UMD library, it can be used in a web client
as in server side node environment.
Installation
serverside
npm install --save lib-r-math.js
web
The module directory contains a minimized bundle for use in html <script>
tag. The library is attached to the window.libR
object after loading.
<script src="https://unpkg.com/lib-r-math.js@1.0.74/dist/lib/libR.min.js"></script>
<script>
const libR = window.libR;
const { Tukey, Normal, Beta, StudentT, Wilcoxon } = libR;
</script>
Table of Contents
Differences with R
Some implementation differences exist with R nmath
- PRNG's are not global singletons, but separate object instances and you can have as many as you want. The programmer has the choice of having different deviate generators sharing a common source PRNG.
- Wilcoxon Sum Rank functions
dwilcox, pwilcox, qwilcox
use a fraction of the memory, (R will give memory allocation errors for samples ~1000). The JS solution allocates memory sparsely.
Helper functions for porting R
programs
Summary
R language operators and function arguments can work with vectorized input
.
These helper functions are used to mimic this functionality and assist porting of scripts from the R ecosystem using libRmath.js
.
div
Divides scalar or an array of values with element of the second array or scalar.
Usage:
const libR = require('lib-r-math.js');
const { div } = libR.R;
div(3, 5);
div([0, 1, 2, 3], 5);
div([10,2,3],[2,4]);
mult
Multiplies scalar or an array of values with another scalar or array of values.
Applies R recycling rules in case of arguments of unequal array length.
Usage:
const libR = require('lib-r-math.js');
const { mult } = libR.R;
mult(3, 5);
mult([0, 1, 2, 3], [5,2]);
asArray
Creates a new function from an existing one for it to always return its result as an array.
Usage:
const libR = require('lib-r-math.js');
const { asArray } = libR.R;
const r = asArray(Math.random);
r()
r()
r()
sum
Analog to R
's sum
function. Calculates the sum of all elements of an array.
const libR = require('lib-r-math.js');
const { sum } = libR.R;
sum(5);
sum([1, 2, 3, 4]);
summary
Gives summary information of numeric data in an array.
typescript decl
declare function summary(data: number[]): ISummary;
interface ISummary {
N: number;
mu: number;
population: {
variance: number;
sd: number;
};
sample: {
variance: number;
sd: number;
};
relX;
relX2;
stats: {
min: number;
'1st Qu.': number;
median: number;
'3rd Qu.': number;
max: number;
};
}
Usage:
const libR = require('lib-r-math.js');
const { summary } = libR.R;
summary([360, 352, 294, 160, 146, 142, 318, 200, 142, 116])
numberPrecision
Truncates numbers to a specified significant digits.
Takes single numeric value as argument or an array of numbers.
Usage:
const libR = require('lib-r-math.js');
const digits4 = libR.R.numberPrecision(4);
const pr4a = digits4(1.12345678);
const pr4b = digits4([0.4553, -2.1243]);
any
Test a Predicate for each element in an Array. Returns true or false depending on a test function.
Usage:
const libR = require('lib-r-math.js');
const any = libR.R.any;
any([1, 2, 3, 4])(x => x < 2);
any([1, 2, 3, 4])(x => x > 5);
arrayrify
(DEPRICATED use multiplex
)
Mimics R vectorized function arguments. Wraps an existing function changing the first first argument to accept both scalar (number) or an array( number[] ).
Note: Only the first argument is vectorized
typescript decl
declare function arrayrify<T, R>(fn: (x: T, ...rest: unknown[]) => R);
R example
c(1,2,3,4)^2
Javascript equivalent
const libR = require('lib-r-math.js');
const { arrayrify } = libR.R;
const pow = arrayrify(Math.pow);
pow(3, 4);
pow([3, 4, 5], 4);
each
Functional analog to Array.prototype.forEach
, but can also loop over object properties.
The return type can be either an new array or a scalar (see Example
).
Example:
const libR = require('lib-r-math.js');
const { each } = libR.R;
each(11)(v => console.log(v * 2)) ;
each([3])(v => console.log(v * 2));
each([11, 12])( (v, idx) => console.log({ v, idx}));
each({ p:1, name:'myname' })( (value, key) => console.log(`${key}=${value}`))
flatten
or c
(alias)
Analog to R's c
function. Constructs a final array by (recursively) flattening and merging all of its arguments which can be a combination of scalars and arrays.
Example:
const libR = require('lib-r-math.js');
const { c } = libR.R;
c(-1, 0, [1], 'r', 'b', [2, 3, [4, 5]]);
map
Functional analog to Array.prototype.map
, but can also loop over object properties.
The return type can be either an new array or a scalar (see Example
).
Example:
const libR = require('lib-r-math.js');
const { map } = libR.R;
map(11)(v => v * 2);
map([3])(v => v * 2);
map([11, 12])( (v, idx) => idx);
map({ p:1, name:'myname' })( (value, key) => `${key}=${value}`)
selector
Filter function generator, to be used with Array.prototype.filter
to pick elements based on their order (zero based index) in the array.
Usually used together with seq
to pick items from an array.
NOTE: Always returns an instance of Array.
Example:
const libR = require('lib-r-math.js');
const { selector } = libR.R;
['an', 'array', 'with', 'some', 'elements'].filter(
selector([0, 2, 3])
);
['an', 'array', 'with', 'some', 'elements'].filter(
selector(3)
);
const seq = libR.R.seq()();
[7, 1, 2, 9, 4, 8, 16].filter(
selector(
seq(0, 6, 2)
)
);
seq
typescript decl
const seq = (adjustUp = 0) => (adjustDown = adjust) => (
start: number,
end: number = 1,
step: number = 1
) => number[];
R analog to the seq
function in R. Generates an array between start
and end
(inclusive) using step
(defaults to 1
). The JS implementation ignores the sign of the
step
argument and only looks at its absolute value.
Like in R, If (end-start)/step
is not an exact integer, seq
will not overstep the bounds while counting up (or down).
Arguments:
adjustUp
: (default 0). If end
>= start
then adjust
value is added to every element in the array.adjustDown
: (default 0). If start
>= end
then adjustMin
value is added to every element in the array.start
: (inclusive) the sequence start valuestop
: defaults to 1
. (inclusive) the sequence stop value if possible with step
step
: defaults to 1
, sign is ignored. Sign is inferred from the values of start
and stop
.
First we look how seq
works in R.
R
seq(1,3,0.5);
seq(7,-2, -1.3);
Equivalent in Javascript
const libR = require('lib-r-math.js');
let seqA = libR.R.seq()();
seqA(1, 5);
seqA(5, -3);
seqA(3)
let seqB = libR.R.seq(1)(-2);
seqB(0, 4);
seqB(6, 5, 0.3);
multiplex
Turns an existing javascript function into one that follows the R argument recycling rule.
Multiplexes the value of several array arguments into one array with the
use of a mapping function.
The length of the result is the maximum of the lengths of the parameters.
All parameters are recycled to that length.
const libR = require('lib-r-math.js');
const { multiplex, c } = libR.R;
const pow = multiplex(Math.pow);
pow([1, 2, 3, 4], 2);
pow(2, [2, 3, 4])
pow([2, 3], [2, 3, 4, 5]);
timeseed
Generates a number based by on your system time clock. Intended use is with
PRNG (re)initialization. Its a synchronized function that will wait for some milliseconds before sampling the system clock and returning a result.
Usage:
const libR = require('lib-r-math.js');
const { rng: { timeseed } } = libR;
timeseed();
Uniform Pseudo Random Number Generators
Summary
In 'R', the functions that generate random deviates of distributions (Example: Poisson (rpois
), Student-t (rt
), Normal (rnorm
), etc) use uniform PRNG's directly or indirectly (as wrapped in a normal distributed PRNG). This section discusses the uniform distributed PRNG's that have been ported from R to JS.
The 7 Uniform Random Number Generators
All 7 uniform random generators have been ported and tested to yield exactly the
same as their R counterpart.
Improvements compared to R
In R it is impossible to use different types of uniform random generators at the
same time because of a global shared seed buffer. In our port every random
generator has its own buffer and can therefore be used concurrently.
General Usage
All uniform random generator classes have these public methods:
init
: set the random generator seed. Same as R set.seed()
seed (read/write property)
: get/set the current seed values as an array. Same as R .Random.seed
.unif_random
: get a random value, same as runif(1)
in R
"Mersenne Twister"
From Matsumoto and Nishimura (1998). A twisted GFSR with period 2^19937 - 1
and equi-distribution in 623 consecutive dimensions (over the whole period). The
seed
is a 624-dimensional set of 32-bit integers plus a current position in
that set.
usage example:
const libR = require('lib-r-math.js');
const {
R: { numberPrecision },
rng: { MersenneTwister, timeseed }
} = libR;
const precision = numberPrecision(9);
const mt = new MersenneTwister(12345);
mt.init(timeseed());
mt.init(0);
mt.seed.slice(0, 8);
const rmt1 = mt.unif_rand(5);
precision(rmt1);
Equivalent in R
RNGkind("Mersenne-Twister")
set.seed(0)
.Random.seed[2:9]
runif(5)
"Wichmann-Hill"
The seed, is an integer vector of length 3, where each element is in 1:(p[i] - 1)
, where p is the length 3 vector of primes, p = (30269, 30307, 30323)
. The
Wichmann–Hill
generator has a cycle length of 6.9536e12 = ( 30269 * 30307 * 30323 )
, see Applied Statistics (1984) 33, 123 which corrects the original
article).
usage example:
const libR = require('lib-r-math.js');
const {
rng: { WichmannHill, timeseed },
R: { numberPrecision }
} = libR;
const precision = numberPrecision(9);
const wh = new WichmannHill(1234);
wh.init(timeseed());
wh.init(0);
wh.seed;
const rwh1 = wh.unif_rand(5);
precision(rwh1);
in R console:
> RNGkind("Wichmann-Hill")
> set.seed(0)
> runif(5)
[1] 0.4625532 0.2658268 0.5772108 0.5107932
[5] 0.3375606
"Marsaglia-Multicarry"
A multiply-with-carry RNG is used, as recommended by George Marsaglia in his
post to the mailing list ‘sci.stat.math’. It has a period of more than 2^60 and
has passed all tests (according to Marsaglia). The seed is two integers (all
values allowed).
usage example:
const libR = require('lib-r-math.js');
const {
rng: { MarsagliaMultiCarry, timeseed },
R: { numberPrecision }
} = libR;
const precision = numberPrecision(9);
const mmc = new MarsagliaMultiCarry(1234);
mmc.init(timeseed());
mmc.init(0);
mmc.seed;
const rmmc = mmc.unif_rand(5);
precision(rmmc);
in R console:
> RNGkind("Marsaglia-Multicarry")
> set.seed(0)
> runif(5)
[1] 0.1691538 0.5315435 0.5946053 0.2333154
[5] 0.4576562
"Super Duper"
Marsaglia's famous Super-Duper from the 70's. This is the original version which
does not pass the MTUPLE
test of the Diehard
battery. It has a period of about
4.6*10^18 for most initial seeds. The seed is two integers (all values allowed
for the first seed: the second must be odd).
We use the implementation by Reeds et al (1982–84).
usage example:
const libR = require('lib-r-math.js');
const {
rng: { SuperDuper, timeseed },
R: { seq, numberPrecision }
} = libR;
const precision = numberPrecision(9);
const sd = new SuperDuper(1234);
sd.init(timeseed());
sd.init(0);
sd.seed;
const rsd1 = sd.unif_rand(5);
precision(rsd1);
in R console:
> RNGkind("Super-Duper")
> set.seed(0)
> runif(5)
[1] 0.6404036 0.5927313 0.4129687 0.1877294
[5] 0.2679058
"Knuth TAOCP"
An earlier version from Knuth (1997).
The 2002 version was not backwards compatible with the earlier version: the
initialization of the GFSR from the seed was altered. R did not allow you to
choose consecutive seeds, the reported ‘weakness’, and already scrambled the
seeds.
usage example:
const libR = require('lib-r-math.js');
const {
rng: { KnuthTAOCP, timeseed },
R: { numberPrecision }
} = libR;
const precision = numberPrecision(9);
const kn97 = new KnuthTAOCP(1234);
kn97.init(timeseed());
kn97.init(0);
kn97.seed;
const rkn97 = kn97.unif_rand(5);
precision(rkn97);
same example in R (click to show)
> RNGkind("Knuth-TAOCP")
> set.seed(0)
> runif(5)
[1] 0.6274008 0.3541867 0.9898934 0.8624081 0.6622992
"Knuth TAOCP 2002"
A 32-bit integer GFSR using lagged Fibonacci sequences with subtraction. That
is, the recurrence used is
X[j] = (X[j-100] - X[j-37]) mod 2^30
and the ‘seed’ is the set of the 100 last numbers (actually recorded as 101
numbers, the last being a cyclic shift of the buffer). The period is around
2129.
usage example:
const libR = require('lib-r-math.js');
const {
rng: { KnuthTAOCP2002, timeseed },
R: { numberPrecision }
} = libR;
const precision = numberPrecision(9);
const kt2002 = new KnuthTAOCP2002(1234);
kt2002.init(timeseed());
kt2002.init(0);
kt2002.seed;
const kt02 = kt2002.unif_rand(5);
precision(kt02);
same example in R (click to show)
> RNGkind("Knuth-TAOCP-2002")
> set.seed(0)
> runif(5)
[1] 0.1958190 0.7538669 0.4724112 0.1931604
[5] 0.1950184
"L'Ecuyer-CMRG":
A ‘combined multiple-recursive generator’ from L'Ecuyer (1999), each element of
which is a feedback multiplicative generator with three integer elements: thus
the seed is a (signed) integer vector of length 6. The period is around 2^191.
The 6 elements of the seed are internally regarded as 32-bit unsigned integers.
Neither the first three nor the last three should be all zero, and they are
limited to less than 4294967087 and 4294944443 respectively.
This is not particularly interesting of itself, but provides the basis for the
multiple streams used in package parallel.
usage example:
const libR = require('lib-r-math.js');
const {
rng: { LecuyerCMRG, timeseed },
R: { numberPrecision }
} = libR;
const precision = numberPrecision(9);
const lc = new LecuyerCMRG(1234);
lc.init(timeseed());
lc.init(0);
lc.seed;
const lc1 = lc.unif_rand(5);
precision(lc1);
in R console:
> RNGkind("L'Ecuyer-CMRG")
> set.seed(0)
> .Random.seed[2:7]
[1] -835792825 1280795612 -169270483 -442010614
[5] -603558397 -222347416
> runif(5)
[1] 0.3329275 0.8903526 0.1639634 0.2990508
[5] 0.3952391
Normal distributed Random Number Generators
Summary
This section discusses the normal distributed PRNG's
that have been ported from R to JS.
All 6 normal random generators
have been ported and tested to yield exactly the same as their R counterpart.
General Use
All normal random generator adhere to the same principles:
-
A constructor that takes an instance of a uniform PRNG as an argument
-
A function norm_random
: get a random value, same as rnorm(1)
in R.
-
A function unif_random
: the underlying uniform PRNG.
-
The default argument for the constructor for normal PRNG is : Mersenne-Twister
.
-
The class instance property rng
contains the wrapped uniform PRNG instance.
-
All PRNG producing normal variates are packaged under the JS library name space rng.normal
.
"Ahrens Dieter"
Ahrens, J. H. and Dieter, U. (1973) Extensions of Forsythe's method for random
sampling from the normal distribution. Mathematics of Computation 27, 927-937.
example usage:
const libR = require('lib-r-math.js');
const {
rng: {
SuperDuper,
normal: { AhrensDieter }
},
R: { numberPrecision }
} = libR;
const precision = numberPrecision(9);
const sd = new SuperDuper(0);
const ad1 = new AhrensDieter(sd);
sd.init(9987);
ad1.rng.init(9987);
const ad2 = new AhrensDieter();
ad2.rng.init(0);
const rngAd = ad2.norm_rand(5);
precision(rngAd);
ad2.unif_rand();
ad2.rng.unif_rand();
in R console
> RNGkind("Mersenne-Twister",normal.kind="Ahrens-Dieter")
> set.seed(0)
> rnorm(5)
[1] -1.1761675 0.6741177 1.0641435 -0.1438973
[5] -1.2311498
> runif(2)
[1] 0.2016819 0.8983897
Box Muller
Box, G. E. P. and Muller, M. E. (1958) A note on the generation of normal random
deviates. Annals of Mathematical Statistics 29, 610–611.
Example usage:
const libR = require('lib-r-math.js');
const {
rng: {
SuperDuper,
normal: { BoxMuller }
},
R: { numberPrecision }
} = libR;
const precision = numberPrecision(9);
const sd = new SuperDuper(0);
const bm1 = new BoxMuller(sd);
sd.init(0);
const bm2 = new BoxMuller();
bm2.rng.init(0);
const bm = bm2.norm_rand(5);
precision(bm);
bm2.unif_rand();
bm2.rng.unif_rand();
R equivalent
> RNGkind("Mersenne-Twister",normal.kind="Box-Muller")
> set.seed(0)
> rnorm(5)
[1] 1.2973876 -0.9843785 -0.7327989 0.7597742
[5] 1.4999888
> runif(2)
[1] 0.8983897 0.9446753
Buggy Kinderman Ramage
Kinderman, A. J. and Ramage, J. G. (1976) Computer generation of normal random variables. Journal of the American Statistical Association 71, 893-896.
The Kinderman-Ramage generator used in versions prior to 1.7.0 (now called "Buggy") had several approximation errors and should only be used for reproduction of old results.
example usage:
const libR = require('lib-r-math.js');
const {
R: { numberPrecision },
rng: { SuperDuper, normal: { BuggyKindermanRamage } }
} = libR;
const precision = numberPrecision(9);
const sd = new SuperDuper(0);
const bkm1 = new BuggyKindermanRamage(sd);
sd.init(0);
bkm1.rng.init(0);
const bkm2 = new BuggyKindermanRamage();
bkm2.rng.init(0);
const bk = bkm2.norm_rand(5);
precision(bk);
bkm2.unif_rand();
bkm2.rng.unif_rand();
in R Console
RNGkind("Mersenne-Twister",normal.kind="Buggy Kinderman-Ramage");
set.seed(0);
rnorm(5);
runif(2);
Inversion
Inverse transform sampling wiki
example usage:
const libR = require('lib-r-math.js');
const {
rng: { SuperDuper, normal: { Inversion } },
R: { numberPrecision }
} = libR;
const precision = numberPrecision(9);
const sd = new SuperDuper(0);
const inv1 = new Inversion(sd);
sd.init(0);
const inv2 = new Inversion();
inv2.rng.init(0);
const in2 = inv2.norm_rand(5);
precision(in2);
inv2.unif_rand();
inv2.rng.unif_rand();
in R console
> RNGkind("Mersenne-Twister",normal.kind="Inversion")
> set.seed(0)
> rnorm(5)
[1] 1.2629543 -0.3262334 1.3297993 1.2724293
[5] 0.4146414
> runif(2)
[1] 0.06178627 0.20597457
Kinderman Ramage
Kinderman, A. J. and Ramage, J. G. (1976) Computer generation of normal random variables. Journal of the American Statistical Association 71, 893-896.
Non "buggy" version
Example usage:
const libR = require('lib-r-math.js');
const {
rng: {
SuperDuper,
normal: { KindermanRamage }
},
R: { numberPrecision }
} = libR;
const precision = numberPrecision(9);
const sd = new SuperDuper(0);
const km1 = new KindermanRamage(sd);
sd.init(1234);
km1.rng.init(1234);
const km2 = new KindermanRamage();
km2.rng.init(0);
const k2 = km2.norm_rand(5);
precision(k2);
km2.unif_rand();
km2.rng.unif_rand();
in R console
> RNGkind("Mersenne-Twister",normal.kind="Kinder")
> set.seed(0)
> rnorm(5)
[1] 0.3216151 1.2325156 0.2803695 -1.1751964
[5] -1.6047136
> runif(2)
[1] 0.1765568 0.6870228
>
Normal and Uniform distributions
Summary
In the Section 1
and 2
we discussed uniform and normal PRNG classes. These classes can be used by themselves but mostly intended to be consumed to generate
random numbers with a particular distribution (like Uniform
, Normal
, Gamma
,
Weibull
, Chi-square
etc).
Uniform distribution
dunif, qunif, punif, runif
See R doc
These functions are created with the factory method Uniform
taking as argument a uniform PRNG. Defaults to Mersenne-Twister.
Usage:
const libR = require('lib-r-math.js');
const {
Uniform,
rng: { SuperDuper }
} = libR;
const uni1 = Uniform(new SuperDuper(0));
const uni2 = Uniform();
const { runif, dunif, punif, qunif } = uni2;
dunif
The density function. See R doc
typescript decl
declare function dunif(
x: number | number[],
min = 0,
max = 1,
asLog = false
): number | number[];
x
: scalar or vector of quantilesmin, max
lower and upper limits of the distribution. Must be finite.asLog
if true
, results are given as ln.
Example:
const libR = require('lib-r-math.js');
const {
Uniform,
R: { numberPrecision, c }
} = libR;
const precision = numberPrecision(9);
const { runif, dunif, punif, qunif } = Uniform();
const x = [-1, 0, 0.4, 1, 2];
const d0 = dunif(0.5);
const d1 = dunif(x);
const d2 = dunif(x, 0, 2);
const d3 = dunif(x, 0, 2, true);
precision(d3);
punif
The probability function. See R doc
typescript decl
declare function punif(
q: number | number[],
min = 0,
max = 1,
lowerTail = true,
logP = false
): number | number[];
x
: scalar or vector of quantilesmin, max
: lower and upper limits of the distribution. Must be finite.lowerTail
: if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x].logP
: if true
, probabilities p are given as ln(p).
Example:
const libR = require('lib-r-math.js');
const {
Uniform,
R: { numberPrecision }
} = libR;
const precision = numberPrecision(9);
const { runif, dunif, punif, qunif } = Uniform();
const q = [-2, 0.25, 0.75, 2];
const p1 = punif(0.25);
const p2 = punif(q);
const p3 = punif(q, 0, 1, false);
precision(p3);
const p4 = punif(q, 0, 2, false, true);
precision(p4);
const p5 = punif(q, 0, 2, true, true);
precision(p5);
qunif
The quantile function. See R doc
typescript decl
declare function qunif(
p: number | number[],
min = 0,
max = 1,
lowerTail = true,
logP = false
): number | number[];
p
: scalar or vector of quantilesmin, max
lower and upper limits of the distribution. Must be finite.lowerTail
if true
(default), probabilities are P[X ≤ x], otherwise, P[X > x].logP
if true
, probabilities p are given as ln(p).
Example:
const libR = require('lib-r-math.js');
const {
Uniform,
R: { numberPrecision, multiplex }
} = libR;
const precision = numberPrecision(9);
const { runif, dunif, punif, qunif } = Uniform();
const p = [0, 0.1, 0.5, 0.9, 1];
const q1 = qunif(0);
const q2 = qunif(p, -1, 1, false);
const log = multiplex(Math.log);
const q3 = qunif(log(p), -1, 1, false, true);
runif
Generates random deviates. See R doc
typescript decl
declare function runif(
n: number = 1,
min: number = 0,
max: number = 1
): number | number[];
n
: number of deviates. Defaults to 1.min, max
lower and upper limits of the distribution. Must be finite.
Example:
const libR = require('lib-r-math.js');
const {
Uniform,
rng: { LecuyerCMRG },
R: { numberPrecision }
} = libR;
const _9 = numberPrecision(9);
const lm = new LecuyerCMRG(1234);
const { runif, dunif, punif, qunif } = Uniform(lm);
const r1 = _9(runif(4));
const r2 = _9(runif(5, -1, 1, true));
Equivalent in R
RNGkind("L'Ecuyer-CMRG");
set.seed(1234);
runif(4);
runif(5,-1,1);
Normal distribution
dnorm, qnorm, pnorm, rnorm
Density, distribution function, quantile function and random generation for the normal distribution with mean equal to mean
and standard deviation equal to sd
. See R doc.
These functions are created with the factory method Normal
taking as optional argument a normal PRNG (defaults to Inversion.
Usage:
import 'lib-r-math.js';
const norm1 = Normal(new rng.AhrensDieter(new rng.SuperDuper(1234)));
const norm2 = Normal();
const { rnorm, dnorm, pnorm, qnorm } = norm2;
dnorm
The density function of the Normal distribution. See [R manual][r-manual-norm].
typescript decl
declare function dnorm(
x: number,
mu = 0,
sd = 1,
log = false
): number;
x
:scalar or array of quantilesmu
: mean, default 0
.sd
: standard deviation, default 1
.log
: give result as ln(..) value, default false
Example: (click to show)
const libR = import 'lib-r-math.js'
window.libR
const { c, numberPrecision, seq0, chain, Rcycle } = libR.utils
const { rnorm, dnorm, pnorm, qnorm } = libR.Normal();
const Dnorm = chain(numberPrecision(9), dnorm)
const d1 = Dnorm(0)
const d2 = Rdnorm(3, 4, 2)
const d3 = Dnorm(-10)
const x = c(-Infinity, Infinity, NaN, seq0(-4, 4))
const d4 = Dnorm(x)
const d5 = Dnorm(x, 0, 1, true)
Equivalent in R
dnorm(0);
dnorm(3, 4, 2);
dnorm(-10)
x = c(-Inf, Inf, NaN, seq(-4, 4));
dnorm(x)
dnorm(x, 0,1, TRUE);
pnorm
The distribution function of the Normal distribution. See [R doc][r-doc-normal].
typescript decl
declare function pnorm(
q: number,
mu = 0,
sd = 1,
lowerTail = true,
log = false
): number;
q
:scalar or array of quantilesmu
: mean (default 0)sd
: standard deviation (default 1)lowerTail
: if true
(default), probabilities are P[X ≤ x], otherwise, P[X > x].log
: give result as log value
Example: (click to show)
const libR = import 'lib-r-math.js'
window.libR
const { c, numberPrecision, seq0, chain, Rcycle } = libR.utils
const { rnorm, dnorm, pnorm, qnorm } = libR.Normal()
const Pnorm = Rcycle(chain( numberPrecision(9), pnorm))
const q = seq0(-1, 1)
const p1 = Pnorm(q);
const p2 = Porm(q, 0, 1, false));
const p3 = Pnorm(q, 0, 1, false, true));
Equivalent in R
pnorm(-1:1);
pnorm(-1:1, lower.tail=FALSE);
pnorm(-1:1, log.p= TRUE);
qnorm
The quantile function of the Normal distribution. See R doc.
typescript decl
declare function qnorm(
p: number,
mu = 0,
sd = 1,
lowerTail = true,
logP = false
): number;
p
: probabilities (scalar or array).mu
: normal mean (default 0).sd
: standard deviation (default 1).logP
: probabilities are given as ln(p).
Example: (click to show)
const libR = require('lib-r-math.js');
window.libR
const { Rcycle, chain, numberPrecision, seq0 } = libR.utils
const log = Rcycle(Math.log)
const _9 = numberPrecision(9)
const { rnorm, dnorm, pnorm, qnorm } = libR.Normal()
const Qnorm = Rcycle(chain(_9 qnorm))
const p = seq(0, 1, 0.25)
const q1 = Qnorm(0)
const q2 = Qnorm(p, 0, 2)
const q3 = Qnorm(p, 0, 2, false)
const q4 = Qnorm(log(p), 0, 2, false, true)
Equivalent in R
p = seq(0, 1, 0.25);
qnorm(0);
qnorm(p, 0, 2);
qnorm(p, 0, 2, FALSE);
qnorm(log(p), 0, 2, FALSE, TRUE);
rnorm
Generates random normal deviates. See R doc.
typescript decl
declare function rnorm(n = 1, mu = 0, sd = 1): number | number[];
n
: number of deviatesmu
: mean of the distribution. Defaults to 0.sd
: standard deviation. Defaults to 1.
Example: (click to show)
const libR = require('lib-r-math.js');
window.libR
const { Normal, R: { numberPrecision } } = libR
const _9 = numberPrecision(9);
const { rnorm, dnorm, pnorm, qnorm } = Normal();
const Rnorm = chain(_9, rnorm)
const r1 = Rnorm(5);
const r2 = Rnorm(5, 2, 3);
Equivalent in R
RNGkind("Mersenne-Twister",normal.kind="Inversion")
set.seed(0)
rnorm(5)
rnorm(5,2,3)
Other Probability Distributions
summary
libRmath.so
contains 19 probability distributions (other then Normal
and Uniform
) with their specific density, quantile and random generators, all are ported and have been verified to yield the same output.
Beta distribution
dbeta, qbeta, pbeta, rbeta
See R doc.
See wiki.
These functions are members of an object created by the Beta
factory method. The factory method needs an instance of an optional normal PRNG. Various instantiation methods are given below.
Usage:
const libR = require('lib-r-math.js');
const { Beta, rng: { SuperDuper, normal: { BoxMuller } } } = libR;
const explicitB = Beta(new BoxMuller(new SuperDuper(0)));
const defaultB = Beta();
const { dbeta, pbeta, qbeta, rbeta } = defaultB;
dbeta
The density function of the Beta distribution.
See R doc.
typescript decl
declare function dbeta(
x: number | number[],
shape1: number,
shape2: number,
ncp = undefined,
asLog = false
): number | number[];
x
: scalar or array of quantiles. 0 <= x <= 1shape1
: non-negative a
parameter of the Beta distribution.shape2
: non-negative b
parameter of the Beta distribution.ncp
: non centrality parameter. Note: undefined
is different then 0
asLog
: return result as ln(p)
const libR = require('lib-r-math.js');
const { Beta, R: { numberPrecision } } = libR;
const _9 = numberPrecision(9);
const { dbeta, pbeta, qbeta, rbeta } = Beta();
const d1 = _9(dbeta(0.4, 2, 2, 1));
const d2 = _9(dbeta(0.4, 2, 2, undefined, true));
const d3 = _9(dbeta(0.4, 2, 2, 1, true));
const d4 = _9(
dbeta(
[0, 0.2, 0.4, 0.8, 1, 1.2],
2,
2)
);
Equivalent in R
dbeta(0.4,2,2, ncp=1)
dbeta(0.4,2,2, log = TRUE)
dbeta(0.4,2,2, ncp=1, TRUE)
dbeta( c(0, 0.2, 0.4, 0.8, 1, 1.2), 2, 2)
pbeta
The cumulative probability function of the Beta distribution. See R doc.
declare function pbeta(
q: number | number[],
shape1: number,
shape2: number,
ncp?: number,
lowerTail: boolean = true,
logP: boolean = false
): number | number[];
p
: quantiles. 0 <= x <= 1shape1
: non-negative a
parameter of the Beta distribution.shape2
: non-negative b
parameter of the Beta distribution.ncp
: non centrality parameter. Note: undefined
is different then 0
lowerTail
: if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x].logP
: return probabilities as ln(p)
Usage:
const libR = require('lib-r-math.js');
const {
Beta,
R: { multiplex, numberPrecision, seq: _seq }
} = libR;
const _9 = numberPrecision(9);
const log = multiplex(Math.log);
const seq = _seq()();
const { dbeta, pbeta, qbeta, rbeta } = Beta();
const q = seq(0, 1, 0.2);
const p1 = _9(pbeta(0.5, 2, 5));
const p2 = _9(pbeta(0.5, 2, 5, 4));
const p3 = _9(pbeta(q, 2, 5, 4));
const p4 = _9(pbeta(q, 2, 5, undefined));
const p5 = _9(pbeta(q, 2, 5, undefined, true, true));
Equivalent in R
q = c(0, 0.2, 0.4, 0.6, 0.8, 1);
pbeta(0.5, 2, 5);
pbeta(0.5, 2, 5, 4)
pbeta(q, 2, 5, 4);
pbeta(q, 2, 5);
pbeta(q, 2, 5, log.p=TRUE)
qbeta
The quantile function of the Beta distribution. See R doc.
typescript decl
declare function qbeta(
p: number | number[],
shape1: number,
shape2: number,
ncp = undefined,
lowerTail = true,
logP = false
): number | number[];
p
: quantiles (scalar or array).shape1
: non-negative a
parameter of the Beta distribution.shape2
: non-negative b
parameter of the Beta distribution.ncp
: non centrality parameter. Note: undefined
is different then 0
lowerTail
: if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x].logP
: return probabilities as ln(p).
Usage:
const libR = require('lib-r-math.js');
const { Beta, R: { multiplex, numberPrecision } } = libR;
const ln = multiplex(Math.log);
const _9 = numberPrecision(9);
const { dbeta, pbeta, qbeta, rbeta } = Beta();
const p = [0, 0.25, 0.5, 0.75, 1];
const q1 = _9(qbeta(0, 99, 66));
const q2 = _9(qbeta(p, 4, 5));
const q3 = _9(qbeta(p, 4, 5, 3));
const q4 = _9(qbeta(p, 4, 5, undefined, false));
const q5 = _9(qbeta(
ln(p),
4,
5,
undefined,
false,
true
));
Equivalent in R
p = c(0,.25,.5,.75,1);
qbeta(0,99,66);
qbeta(p, 4,5);
qbeta(p, 4,5,3);
qbeta(p, 4,5, lower.tail = FALSE);
qbeta( log(p) ,4,5, lower.tail = FALSE, log.p=TRUE);
rbeta
Generates random deviates for the Beta distribution. See R doc.
typescript decl
declare function rbeta(
n: number,
shape1: number,
shape2: number,
ncp = 0
): number | number[];
n
: number of deviatesshape1
: non-negative a
parameter of the Beta distribution.shape2
: non-negative b
parameter of the Beta distribution.ncp
: non centrality parameter.
const libR = require('lib-r-math.js');
const {
Beta,
rng: {
LecuyerCMRG,
normal: { Inversion }
},
R: { multiplex, numberPrecision }
} = libR;
const ln = multiplex(Math.log);
const _9 = numberPrecision(9);
const lc = new LecuyerCMRG(0);
const { dbeta, pbeta, qbeta, rbeta } = Beta(new Inversion(lc));
const r1 = _9(rbeta(5, 0.5, 0.5));
const r2 = _9(rbeta(5, 2, 2, 4));
lc.init(0);
const r3 = _9(rbeta(5, 2, 2));
const r4 = _9(rbeta(5, 2, 2, 5));
Same values as in R
Equivalent in R
RNGkind("L'Ecuyer-CMRG", normal.kind ="Inversion")
set.seed(0)
rbeta(5, 0.5, 0.5)
rbeta(5, 2, 2, 4)
set.seed(0)
rbeta(5, 2, 2);
rbeta(5, 2, 2, 5);
Binomial distribution
dbinom, qbinom, pbinom, rbinom
See R doc and wiki.
These functions are members of an object created by the Binomial
factory method. The factory method needs an instance of a normal PRNG. Various instantiation methods are given below.
Usage:
const libR = require('lib-r-math.js');
const { Binomial, rng: { LecuyerCMRG } } = libR;
const lc = new LecuyerCMRG(0);
const explicitB = Binomial(lc);
const defaultB = Binomial();
const { dbinom, pbinom, qbinom, rbinom } = defaultB;
dbinom
The density function of the Binomial distribution. See R doc
$$p(x) = \frac{n!}{x!(n-x)!} p^{x} (1-p)^{n-x}$$
typescript decl
declare function dbinom(
x: number,
size: number,
p: number,
asLog = false
): number | number[];
x
: scalar or array of quantiles.size
: number of trailsp
: probability of success.asLog
: return result as ln(p)
Usage:
const libR = require('lib-r-math.js');
const {
Binomial,
R: { numberPrecision, seq: _seq }
} = libR;
const _9 = numberPrecision(9);
const seq = _seq()();
const x = seq(1, 4);
const { dbinom, pbinom, qbinom, rbinom } = Binomial();
const d1 = _9(dbinom(2, 4, 0.3));
const d2 = _9(dbinom(2, 4, 0.3, true));
const d3 = _9(dbinom(x, 4, 0.3));
const d4 = _9(dbinom(x, 4, 0.3, true));
Equivalent in R
dbinom(2,4,0.3)
dbinom(2,4,0.3, TRUE)
dbinom(c(1,2,3,4),4,0.3)
dbinom(c(1,2,3,4),4,0.3, TRUE)
pbinom
The cumulative probability function of the Binomial distribution. See R doc
declare function pbinom(
q: number | number[],
size: number,
prob: number,
lowerTail = true,
logP = false
): number | number[];
q
: scalar or array of quantiles.size
: number of trailsprob
: probability of success.lowerTail
: if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x].logP
: return result as ln(p)
Usage:
const libR = require('lib-r-math.js');
const {
Binomial,
R: { numberPrecision, seq: _seq }
} = libR;
const _9 = numberPrecision(9);
const seq = _seq()();
const { dbinom, pbinom, qbinom, rbinom } = Binomial();
const q = seq(0, 4);
const p1 = pbinom(4, 4, 0.5);
const p2 = _9(pbinom(q, 4, 0.5));
const p3 = _9(pbinom(q, 4, 0.5, false, true));
Equivalent in R
q = c(0, 1, 2, 3, 4);
pbinom(4, 4, 0.5)
pbinom(q, 4, 0.5)
pbinom(q, 4, 0.5, FALSE, TRUE)
qbinom
The quantile function of the Binomial distribution. See R doc
typescript decl
declare function qbinom(
p: number | number[],
size: number,
prob: number,
lowerTail = true,
logP = false
): number | number[];
p
: scalar or array of quantiles.size
: number of trailsprob
: probability of success.lowerTail
: if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x].LogP
: return result as ln(p)
Usage:
const libR = require('lib-r-math.js');
const {
Binomial,
R: { multiplex, numberPrecision, seq: _seq }
} = libR;
const _9 = numberPrecision(9);
const log = multiplex(Math.log);
const seq = _seq()();
const { dbinom, pbinom, qbinom, rbinom } = Binomial();
const p = seq(0, 1, 0.25);
const q1 = _9(qbinom(0.25, 4, 0.3));
const q2 = _9(qbinom(p, 40, 0.3));
const q3 = _9(qbinom(p, 40, 0.3, false));
const q4 = _9(qbinom(log(p), 40, 0.3, false, true));
Equivalent in R
p = seq(0,1,0.25);
qbinom(.25,4,.3)
qbinom(p, 40,.3)
qbinom(p, 40,.3, FALSE)
qbinom(log(p), 40,.3, FALSE, TRUE)
rbinom
Generates random beta deviates for the Binomial distribution. See R doc.
typescript decl
declare function rbinom(
n: number,
size: number,
prop: number
): number | number[];
n
: number of deviatessize
: number of trailsprob
: probability of success.
Usage:
const libR = require('lib-r-math.js');
const {
Binomial,
rng: { KnuthTAOCP2002 }
} = libR;
const kn = new KnuthTAOCP2002(1234);
const { dbinom, pbinom, qbinom, rbinom } = Binomial(kn);
const r1 = rbinom(2, 40, 0.5);
const r2 = rbinom(3, 20, 0.5);
const r3 = rbinom(2, 10, 0.25);
Equivalent in R
RNGkind("Knuth-TAOCP-2002")
set.seed(1234)
rbinom(2, 40, 0.5);
rbinom(3, 20, 0.5);
rbinom(2, 10, 0.25);
Negative Binomial distribution
dnbinom, pnbinom, qnbinom, rnbinom.
See [R doc](https: //stat.ethz.ch/R-manual/R-devel/library/stats/html/NegBinomial.html)
See wiki
These functions are members of an object created by the NegativeBinomial
factory method. This factory method needs an instance of a normal PRNG. Various instantiation methods are given below.
Usage:
const libR = require('lib-r-math.js');
const {
NegativeBinomial,
rng: {
SuperDuper,
normal: { BoxMuller }
}
} = libR;
const bm = new BoxMuller(new SuperDuper(0));
const explicitNB = NegativeBinomial(bm);
const defaultNB = NegativeBinomial();
const { dnbinom, pnbinom, qnbinom, rnbinom } = defaultNB;
dnbinom
The density function of the Negative Binomial distribution.
$$ \frac{Γ(x+n)}{Γ(n) x!} p^{n} (1-p)^{x} $$
See [R doc]
(https: //stat.ethz.ch/R-manual/R-devel/library/stats/html/NegBinomial.html).
typescript decl
declare function dnbinom(
x: number | number[],
size: number,
prob?: number,
mu?: number,
asLog = false
): number | number[];
x
: non-negative integer quantiles. Number of failures before reaching size
successes.size
: target for number of successful trials, or dispersion parameter (the shape parameter of the gamma mixing distribution). Must be strictly positive, need not be integer.prob
: probability of success in each trial. 0 < prob <= 1mu
: alternative parametrization via mean: see ‘Details’ section.asLog
: if true
, probabilities p are given as ln(p).
Usage:
const libR = require('lib-r-math.js');
const {
NegativeBinomial,
R: { seq: _seq, numberPrecision }
} = libR;
const seq = _seq()();
const _9 = numberPrecision(9);
const { dnbinom, pnbinom, qnbinom, rnbinom } = NegativeBinomial();
const x = seq(0, 10, 2);
const d1 = _9(dnbinom(x, 3, 0.5));
const d2 = _9(dnbinom(x, 3, undefined, 3 * (1 - 0.5) / 0.5));
const d3 = _9(dnbinom(x, 3, undefined, 3 * (1 - 0.5) / 0.5, true));
Equivalent in R
dnbinom(0:10, size = 3, prob = 0.5);
dnbinom(0:10, size = 3, mu = 3*(1-0.5)/0.5);
dnbinom(0:10, size = 3, mu = 3*(1-0.5)/0.5, log=T);
pnbinom
The gives the cumulative probability function of the Negative Binomial distribution.
See [R doc](https: //stat.ethz.ch/R-manual/R-devel/library/stats/html/NegBinomial.html).
typescript decl
declare function pnbinom(
q: number | number[],
size: number,
prob?: number,
mu?: number,
lowerTail = true
logP = false
): number|number[]
q
: non-negative integer quantiles.size
: target for number of successful trials, or dispersion parameter (the shape parameter of the gamma mixing distribution). Must be strictly positive, need not be integer.prob
: probability of success in each trial. 0 < prob <= 1mu
: alternative parametrization via mean: see ‘Details’ section.lowerTail
: if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x].logP
: if true
, probabilities p are given as ln(p).
Usage:
const libR = require('lib-r-math.js');
const {
NegativeBinomial,
R: { numberPrecision, seq: _seq, c }
} = libR;
const seq = _seq()();
const _9 = numberPrecision(9);
const { dnbinom, pnbinom, qnbinom, rnbinom } = NegativeBinomial();
const x = c(seq(0, 6), Infinity);
const p1 = _9(pnbinom(x, 3, 0.5));
const p2 = _9(pnbinom(x, 3, undefined, 3 * (1 - 0.5) / 0.5));
const p3 = _9(pnbinom(x, 3, 0.5, undefined, false));
const p4 = _9(pnbinom(x, 3, 0.5, undefined, false, true));
Equivalent in R
x = c(seq(0, 6), Inf);
pnbinom(x, 3, 0.5)
pnbinom(x, size=3, mu=3*(1-0.5)/0.5)
pnbinom(x, size=3, prob=0.5, lower.tail=FALSE);
pnbinom(x, size=3, prob=0.5, lower.tail=FALSE, log.p=TRUE);
qnbinom
The quantile function of the
[Negative Binomial distribution]
(https://en.wikipedia.org/wiki/Negative_binomial_distribution).
See R doc.
typescript decl
declare function qnbinom(
p: number | number[],
size: number,
prob?: number,
mu?: number,
lowerTail = true,
logP = false
): number | number[];
p
: probabilities (scalar or array).size
: target for number of successful trials, or dispersion parameter (the shape parameter of the gamma mixing distribution). Must be strictly positive, need not be integer.prob
: probability of success in each trial. 0 < prob <= 1mu
: alternative parametrization via mean: see ‘Details’ section.lowerTail
: if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x].logP
: if true
, probabilities p are given as ln(p).
Usage:
const libR = require('lib-r-math.js');
const {
NegativeBinomial,
R: { numberPrecision, seq: _seq, multiplex }
} = libR;
const _9 = numberPrecision(9);
const log = multiplex(Math.log);
const seq = _seq()();
const { dnbinom, pnbinom, qnbinom, rnbinom } = NegativeBinomial();
const p = seq(0, 1, 0.2);
const q1 = _9(qnbinom(p, 3, 0.5));
const q2 = _9(qnbinom(p, 3, 0.5, undefined, false));
const q3 = _9(qnbinom(log(p), 3, 0.5, undefined, false, true));
Equivalent in R
p = seq(0, 1, 0.2);
qnbinom(p, 3, 0.5);
qnbinom(p, 3, 0.5, lower.tail = FALSE);
qnbinom(log(p),3,0.5, lower.tail = FALSE, log.p = TRUE);
rnbinom
Generates random deviates for the
[Negative binomial distribution]
(https://en.wikipedia.org/wiki/Negative_binomial_distribution).
See [R doc](https: //stat.ethz.ch/R-manual/R-devel/library/stats/html/NegBinomial.html).
typescript decl
declare function rnbinom(
n: number,
size: number,
prob: number
): number | number[];
n
: ensemble size.size
: target of successful trials.prob
: probability of success in each trial. 0 < prob <= 1
Usage:
const libR = require('lib-r-math.js');
const {
NegativeBinomial,
rng: { SuperDuper, normal: { BoxMuller } }
} = libR;
const bm = new BoxMuller(new SuperDuper(12345));
const { dnbinom, pnbinom, qnbinom, rnbinom } = NegativeBinomial(bm);
const r1 = rnbinom(7, 100, 0.5);
const r2 = rnbinom(7, 100, 0.1);
const r3 = rnbinom(7, 100, 0.9);
bm.rng.init(98765);
const r4 = rnbinom(7, 100, undefined, 100 * (1 - 0.5) / 0.5);
Equivalent in R
RNGkind("Super-Duper", normal.kind="Box-Muller")
set.seed(12345);
rnbinom(7, 100, 0.5);
rnbinom(7, 100, 0.1);
rnbinom(7, 100, 0.9);
set.seed(98765)
rnbinom(7,100, mu= 100*(1-0.5)/0.5)
Cauchy distribution
dcauchy, qcauchy, pcauchy, rcauchy
See R doc. See wiki
These functions are members of an object created by the Cauchy
factory method. The factory method needs as optional argument an instance of one of the uniform PRNG generators.
Usage:
const libR = require('lib-r-math.js');
const { Cauchy, rng: { WichmannHill } } = libR;
const wh = new WichmannHill(1234);
const explicitC = Cauchy(wh);
const defaultC = Cauchy();
const { dcauchy, pcauchy, qcauchy, rcauchy } = defaultC;
dcauchy
The density function of the The Cauchy density. See R doc.
Lemma formula: s
is the "scale" parameter and l
is the "location" parameter.
$$ f(x) = \frac{1}{ π s (1 + ( \frac{x-l}{s} )^{2}) } $$
typescript decl
declare function dcauchy(
x: number | number[],
location = 0,
scale = 1,
asLog = false
): number | number[];
x
: scalar or array of quantile(s).location
: the location parameter, default 0.scale
: the scale parameter, default 1.asLog
: return values as ln(p)
Usage:
const libR = require('lib-r-math.js');
const {
Cauchy,
R: { numberPrecision, seq: _seq }
} = libR;
const seq = _seq()();
const _9 = numberPrecision(9);
const { dcauchy, pcauchy, qcauchy, rcauchy } = Cauchy();
const x = seq(-4, 4, 2);
const d1 = _9(dcauchy(x, -2, 0.5));
const d2 = _9(dcauchy(x, -2, 0.5, true));
const d3 = _9(dcauchy(x, 0, 2));
Equivalent in R
x=seq(-4,4,2);
dcauchy(seq(-4,4,2), location=-2, scale=0.5);
dcauchy(seq(-4,4,2), location=-2, scale=0.5, log=TRUE);
dcauchy(seq(-4,4,2), location=0, scale=2);
pcauchy
The cumulative probability function of the Cauchy distribution. See R doc.
typescript decl
declare function pcauchy(
q: T,
location = 0,
scale = 1,
lowerTail = true,
logP = false
): T;
q
: Scalar or array of quantile(s).location
: The location parameter, default 0.scale
: The scale parameter, default 1.lowerTail
: If TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x].logP
: If TRUE, probabilities p are given as ln(p).
Usage:
const libR = require('lib-r-math.js');
const { Cauchy, R: { numberPrecision } } = libR;
const seq = libR.R.seq()();
const _9 = numberPrecision(9);
const { dcauchy, pcauchy, qcauchy, rcauchy } = Cauchy();
const x = seq(-4, 4, 2);
const p1 = _9(pcauchy(x, -2, 0.5));
const p2 = _9(pcauchy(x, -2, 0.5, true, true));
const p3 = _9(pcauchy(x, 0, 2));
Equivalent in R
x=seq(-4,4,2)
pcauchy(x, location=-2, scale=0.5);
pcauchy(x, location=-2, scale=0.5, log=TRUE);
pcauchy(x, location=0, scale=2);
qcauchy
The quantile function of the Cauchy distribution. See R doc.
typescript decl
declare function qcauchy(
p: number | number[],
location = 0,
scale = 1,
lowerTail = true,
logP = false
): number | number[];
p
: Scalar or array of probabilities(s).location
: The location parameter, default 0.scale
: The scale parameter, default 1.lowerTail
: If TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x].logP
: If TRUE, probabilities p are given as ln(p).
Usage:
const libR = require('lib-r-math.js');
const { Cauchy, R: { numberPrecision, seq: _seq } } = libR;
const seq = _seq()();
const _9 = numberPrecision(9);
const { dcauchy, pcauchy, qcauchy, rcauchy } = Cauchy();
const x = seq(0, 1, 0.2);
const q1 = _9(qcauchy(x, -2, 0.5));
const q2 = _9(qcauchy(x, -2, 0.5, false));
const q3 = _9(qcauchy(x, 0, 2));
Equivalent in R
x = seq(0, 1, 0.2);
qcauchy(x, -2, 0.5);
qcauchy(x, -2, 0.5, lower.tail=FALSE)
qcauchy(x, 0, 2);
rcauchy
Generates random deviates from the Cauchy distribution. See R doc.
typescript decl
declare function rcauchy(
n: number,
location = 0,
scale = 1
): number | number[];
n
: number of deviates to generate.location
: The location parameter, default 0.scale
: The scale parameter, default 1.
Usage:
const libR = require('lib-r-math.js');
const {
Cauchy,
rng: { SuperDuper },
R: { numberPrecision }
} = libR;
const _9 = numberPrecision(9);
const sd = new SuperDuper();
const { dcauchy, pcauchy, qcauchy, rcauchy } = Cauchy(sd);
sd.init(43210);
const r1 = _9(rcauchy(5, 0, 0.5));
const r2 = _9(rcauchy(5, 2, 2));
sd.init(9876);
const r3 = _9(rcauchy(5, -2, 0.25));
Equivalent in R
RNGkind("Super-Duper");
set.seed(43210)
rcauchy(5, 0, 0.5);
rcauchy(5, 2, 2);
set.seed(9876)
rcauchy(5, -2, 0.25);
Chi-Squared (non-central) Distribution
dchisq, qchisq, pchisq, rchisq
These functions are members of an object created by the ChiSquared
factory method. The factory method needs as optional argument an instance of a normal PRNG. See wiki. See R doc
Usage:
const libR = require('lib-r-math.js');
const { ChiSquared, rng: { WichmannHill, normal: { AhrensDieter } } } = libR;
const defaultChi = ChiSquared();
const wh = new WichmannHill();
const explicitChi = ChiSquared(new AhrensDieter(wh));
const { dchisq, pchisq, qchisq, rchisq } = explicitChi;
dchisq
The X2 density function, see R doc.
$$ f_{n}(x) = \frac{1}{2^{\frac{n}{2}} Γ(\frac{n}{2})} x^{\frac{n}{2}-1} e^{\frac{-x}{2}} $$
typescript decl
declare function dchisq(
x: number | number[],
df: number,
ncp?: number,
asLog: boolean = false
): number | number[];
x
: quantiles (array or scalar).df
: degrees of freedom.ncp
: non centrality parameter, default undefined.asLog
: return probabilities as ln(p), default false.
Usage:
const libR = require('lib-r-math.js');
const {
ChiSquared,
R: {
numberPrecision,
seq: _seq
}
} = libR;
const { dchisq, pchisq, qchisq, rchisq } = ChiSquared();
const seq = _seq()();
const _9 = numberPrecision(9);
const x = seq(0, 10, 2);
const d1 = _9(dchisq(x, 5));
const d2 = _9(dchisq(x, 3, 4));
const d3 = _9(dchisq(x, 3, 4, true));
Equivalent in R
x=seq(0, 10, 2);
dchisq(x, 5);
dchisq(x, 3, 4);
dchisq(x, 3, 4, TRUE);
pchisq
The X2 cumulative probability function, see R doc.
typescript decl
declare function pchisq(
q: number | number[],
df: number,
ncp?: number,
lowerTail = true,
logP = false
): number | number[];
q
: quantiles (array or scalar).df
: degrees of freedom.ncp
: non centrality parameter.lowerTail
: if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x].logP
: return probabilities as ln(p)
Usage:
const libR = require('lib-r-math.js');
const {
ChiSquared,
R: { numberPrecision, seq: _seq, c }
} = libR;
const _9 = numberPrecision(9);
const seq = _seq()();
const { dchisq, pchisq, qchisq, rchisq } = ChiSquared();
const q = c(seq(0, 10, 2), Infinity);
const p1 = _9(pchisq(q, 3));
const p2 = _9(pchisq(q, 8, 4, false));
const p3 = _9(pchisq(q, 8, 4, true, true));
Equivalent in R
q = c(seq(0, 10, 2), Inf);
pchisq(q, 3);
pchisq(q, 8, 4, lower.tail=FALSE);
pchisq(q, 8, 4, lower.tail=TRUE, log.p=TRUE);
qchisq
The X2 quantile function, see R doc.
typescript decl
declare function qchisq(
p: number | number[],
df: number,
ncp?: number,
lowerTail = true,
logP = false
): number | number[];
p
: probabilities (array or scalar).df
: degrees of freedom.ncp
: non centrality parameter.lowerTail
: if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x].logP
: probabilities are as ln(p)
Usage:
const libR = require('lib-r-math.js');
const {
ChiSquared,
R: { multiplex, numberPrecision, seq: _seq }
} = libR;
const seq = _seq()();
const log = multiplex(Math.log);
const _9 = numberPrecision(9);
const { dchisq, pchisq, qchisq, rchisq } = ChiSquared();
const p = seq(0, 1, 0.2);
const q1 = _9(qchisq(p, 3));
const q2 = _9(qchisq(p, 50, undefined, false));
const q3 = _9(qchisq(log(p), 50, 0, false, true));
Equivalence in R
p=seq(0, 1, 0.2);
qchisq(p, 3);
qchisq(p, 50, lower.tail=FALSE);
qchisq(log(p), 50, 0, lower.tail=FALSE, log.p=TRUE);
rchisq
Creates random deviates for the X2 distribution, see R doc.
typescript decl
declare function rchisq(
n: number,
df: number,
ncp?: number
): number | number[];
p
: probabilities (array or scalar).df
: degrees of freedom.ncp
: non centrality parameter.
Usage:
const libR = require('lib-r-math.js');
const {
ChiSquared,
rng: {
LecuyerCMRG,
normal: { AhrensDieter }
},
R: { numberPrecision }
} = libR;
const _9 = numberPrecision(9);
const lc = new LecuyerCMRG(1234);
const { dchisq, pchisq, qchisq, rchisq } = ChiSquared(new AhrensDieter(lc));
const r1 = _9(rchisq(5, 6));
const r2 = _9(rchisq(5, 40, 3));
const r3 = _9(rchisq(5, 20));
Equivalent in R
RNGkind("L'Ecuyer-CMRG", normal.kind="Ahrens-Dieter")
set.seed(1234)
rchisq(5, 6);
rchisq(5, 40, 3);
rchisq(5, 20);
Exponential Distribution
dexp, qexp, pexp, rexp
See R doc
These functions are members of an object created by the Exponential
factory method. The factory method needs as optional argument an instance of an uniform PRNG class.
Usage:
const libR = require('lib-r-math.js');
const { Exponential, rng: { MarsagliaMultiCarry } } = libR;
const defaultExponential = Exponential();
const mmc = new MarsagliaMultiCarry(123456);
const customExponential = Exponential(mmc);
const { dexp, pexp, qexp, rexp } = defaultExponential;
dexp
The Exponential density function, see R doc.
$$ f(x) = λ {e}^{- λ x} $$
typescript decl
declare function dexp(
x: number | number[],
rate: number = 1,
asLog: boolean = false
): number | number[];
x
: quantiles (array or scalar).rate
: the λ parameter.asLog
: return probabilities as ln(p)
Usage:
const libR = require('lib-r-math.js');
const { Exponential, R: { numberPrecision } } = libR;
const seq = libR.R.seq()();
const precision = numberPrecision(9);
const { dexp, pexp, qexp, rexp } = Exponential();
const x = seq(0, 0.3, 0.05);
const d1 = dexp(x, 3);
precision(d1);
const d2 = dexp(x, 3, true);
precision(d2);
const d3 = dexp(x, 0.2);
precision(d3);
Equivalent in R
x = seq(0, 0.3, 0.05);
dexp(x, 3)
dexp(x, 3, TRUE)
dexp(x, 0.2)
pexp
The cumulative probability of the Exponential distribution, see R doc.
typescript decl
declare function pexp(
q: number | number[],
rate: number = 1,
lowerTail: boolean = true,
logP: boolean = false
): number | number[];
q
: quantiles (array or scalar).rate
: the λ parameter.lowerTail
: if TRUE (default), probabilities are P[X ≤ q], otherwise, P[X > q].logP
: return probabilities as ln(p)
Usage:
const libR = require('lib-r-math.js');
const { Exponential, R: { numberPrecision } } = libR;
const seq = libR.R.seq()();
const precision = numberPrecision(9);
const { dexp, pexp, qexp, rexp } = Exponential();
const q = seq(0, 0.3, 0.05);
const p1 = pexp(q, 3);
precision(p1);
const p2 = pexp(q, 7, false, true);
precision(p2);
const p3 = pexp(seq(0, 10, 2), 0.2);
precision(p3);
Equivalent in R
q = seq(0, 0.3, 0.05);
pexp(q, 3);
pexp(q, 7, FALSE, TRUE);
pexp(seq(0,10,2),0.2)
qexp
The quantile function of the Exponential distribution, see R doc.
typescript decl
declare function qexp(
p: number | number[],
rate: number = 1,
lowerTail = true,
logP = false
): number | number[];
p
: probabilities (array or scalar).rate
: the λ parameter.lowerTail
: if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x].logP
: return probabilities as ln(p)
Usage:
const libR = require('lib-r-math.js');
const { Exponential, R: { arrayrify, numberPrecision } } = libR;
const log = arrayrify(Math.log);
const seq = libR.R.seq()();
const precision = numberPrecision(9);
const { dexp, pexp, qexp, rexp } = Exponential();
const q = seq(0, 10, 2);
const pp1 = pexp(q, 0.2);
const q1 = qexp(log(pp1), 0.2, true, true);
precision(q1);
const pp2 = pexp(seq(0, 10, 2), 0.2);
const q2 = qexp(pp1, 0.2);
precision(q2);
const pp3 = pexp(seq(0, 0.3, 0.05), 3);
const q3 = qexp(pp3, 3);
precision(q3);
Equivalent in R
q = seq(0,10,2);
pp1 = pexp(q,0.2);
qexp(log(pp1),0.2, TRUE, TRUE)
pp2 = pexp(q ,0.2);
qexp(pp2,0.2)
pp3 = pexp(seq(0, 0.3, 0.05), 3);
q3 = qexp(pp3,3)
rexp
Creates random deviates for the Exponential distribution, see R doc.
typescript decl
declare function rexp(n: number, rate: number = 1): number | number[];
n
: number of deviates to generate (array or scalar).rate
: the λ parameter.
Usage:
const libR = require('lib-r-math.js');
const { Exponential, rng: { WichmannHill }, R: { numberPrecision } } = libR;
const precision = numberPrecision(9);
const wh = new WichmannHill(1234);
const { dexp, pexp, qexp, rexp } = Exponential(wh);
wh.init(12345);
const r1 = rexp(5);
precision(r1);
const r2 = rexp(5, 0.1);
precision(r2);
const r3 = rexp(5, 3);
precision(r3);
Equivalent in R
RNGkind("Wichmann-Hill")
set.seed(12345)
rexp(5)
rexp(5,0.1)
rexp(5,3)
F (non-central) Distribution
df, qf, pf, rf
See R doc
These functions are members of an object created by the FDist
factory method. The factory method needs as optional argument an instance of one of the normal PRNG's.
Usage:
const libR = require('lib-r-math.js');
const {
FDist,
rng: {
MersenneTwister,
normal: { KindermanRamage }
}
} = libR;
const defaultF = FDist();
const mt = new MersenneTwister(1234);
const customF = FDist(new KindermanRamage(mt));
const { df, pf, qf, rf } = customF;
df
The density function of the F distribution. See R doc
With df1
and df2
degrees of freedom:
$$ \large f(x) = \frac{ Γ(\frac{df1 + df2}{2}) } { Γ(\frac{df1}{2}) Γ(\frac{df2}{2}) } {(\frac{n1}{n2})}^{(\frac{df1}{2})} x^{(\frac{df1}{2} - 1)} (1 + \frac{df1}{df2} x)^{-(n1 + n2)/2} $$
typescript decl
declare function df(
x: number | number[],
df1: number,
df2: number,
ncp?: number,
asLog: boolean = false
): number | number[];
x
: quantiles (array or scalar).df1
: degrees of freedom. Infinity
is allowed.df2
: degrees of freedom. Infinity
is allowed.ncp
: non-centrality parameter. If omitted the central F is assumed.asLog
: if TRUE, probabilities p are given as ln(p).
Usage:
const libR = require('lib-r-math.js');
const { FDist, R: { numberPrecision } } = libR;
const seq = libR.R.seq()();
const precision = numberPrecision(9);
const { df, pf, qf, rf } = FDist();
const x = seq(0, 4, 0.5);
const d1 = df(x, 5, 10, 8);
precision(d1);
const d2 = df(x, 50, 10, undefined, true);
precision(d2);
const d3 = df(x, 6, 25);
precision(d3);
const d4 = df(x, 6, 25, 8, true);
precision(d4);
Equivalence in R
x = seq(0, 4, 0.5);
df(x, df1=5,df2=10, ncp=8)
df(x, df1=50,df2=10, log = TRUE)
df(x, 6, 25)
df(x, 6, 25, 8, log=TRUE)
pf
The cumulative probability function of the F distribution. See R doc.
typescript decl
declare function pf(
q: number[] | number,
df1: number,
df2: number,
ncp?: number,
lowerTail: boolean = true,
logP: boolean = false
): number[] | number;
q
: quantiles (array or scalar).df1
: degrees of freedom. Infinity
is allowed.df2
: degrees of freedom. Infinity
is allowed.ncp
: non-centrality parameter. If omitted the central F is assumed.lowerTail
: if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x].asLog
: if TRUE, probabilities p are given as ln(p).
Usage:
const libR = require('lib-r-math.js');
const {
FDist,
R: { numberPrecision }
} = libR;
const seq = libR.R.seq()();
const precision = numberPrecision(9);
const { df, pf, qf, rf } = FDist();
const x = seq(0, 4, 0.5);
const p1 = pf(x, 5, 10, 8);
precision(p1);
const p2 = pf(x, 50, 10, undefined, false);
pecision(p2);
const p3 = pf(x, 50, 10, undefined, false, true);
precision(p3);
const p4 = pf(x, 6, 25, 8, undefined, true);
precision(p4);
Equivalent in R
x = seq(0, 4, 0.5);
pf(x, 5, 10, 8);
pf(x, 50, 10, lower.tail=FALSE);
pf(x, 50, 10, lower.tail=FALSE, log.p=TRUE);
pf(x, 6, 25, 8, log.p=TRUE);
qf
The quantile function of the F distribution. See R doc.
typescript decl
declare function qf(
p: number | number[],
df1: number,
df2: number,
ncp?: number,
lowerTail: boolean = true,
logP: boolean = false
): number | number[];
p
: probabilities (array or scalar).df1
: degrees of freedom. Infinity
is allowed.df2
: degrees of freedom. Infinity
is allowed.ncp
: non-centrality parameter. If omitted the central F is assumed.lowerTail
: if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x].asLog
: if TRUE, probabilities p are given as ln(p).
Usage:
const libR = require('lib-r-math.js');
const { FDist } = libR;
const seq = libR.R.seq()();
const precision = libR.R.numberPrecision(9);
const { df, pf, qf, rf } = FDist();
const q = [ ...seq(0,4), Infinity];
const pp1 = pf(q, 50, 10, undefined, false);
const q1 = qf( pp1, 50, 10, undefined, false);
precision(q1);
const pp2 = pf(q, 50, 10, 9, false, true);
const q2 = qf(pp2, 50, 10, 9, false, true);
precision(q2);
const pp3 = pf(q, 6, 25, 8);
const q3 = qf(pp3, 6, 25, 8);
precision(q3);
const pp4 = pf(q, 3, 9000, undefined, false);
const q4 = qf(pp4, 3, 9000, undefined, false);
Equivlent in R
q = c( seq(0,4), Inf);
pp1=pf(q, 50, 10, lower.tail=FALSE);
qf(pp1, 50, 10, lower.tail=FALSE);
pp2 = pf(q, 50, 10, 9, lower.tail=FALSE, log.p=TRUE);
qf(pp2, 50, 10, 9, lower.tail=FALSE, log.p=TRUE);
pp3 = pf(q, 6, 25, 8);
qf(pp3, 6, 25, 8);
pp4 = pf(q, 3, 9000, lower.tail=FALSE);
qf(pp4, 3, 9000, lower.tail=FALSE);
rf
Generates deviates for the F distribution. See R doc.
typescript decl
declare function rf(
n: number,
df1: number,
df2: number,
ncp?: number
): number | number[];
n
: number of deviates to generate.df1
: degrees of freedom. Infinity
is allowed.df2
: degrees of freedom. Infinity
is allowed.ncp
: non-centrality parameter. If omitted the central F is assumed.
Usage:
const libR = require('lib-r-math.js');
const {
FDist,
rng: {
MersenneTwister,
normal: { KindermanRamage }
},
R: { numberPrecision }
} = libR;
const seq = libR.R.seq()();
const precision = numberPrecision(9);
const mt = new MersenneTwister(1234);
const { df, pf, qf, rf } = FDist(new KindermanRamage(mt));
precision(rf(5, 8, 6));
precision(rf(5, Infinity, Infinity));
precision(rf(5, 40, Infinity, 0));
precision(rf(5, 400, Infinity));
in R Console:
RNGkind("Mersenne-Twister", normal.kind="Kinderman-Ramage");
set.seed(1234);
rf(5,8,6)
rf(5, Inf, Inf)
rf(5, 40, Inf, 0)
rf(5, 400, Inf)
Gamma distribution
dgamma, qgamma, pgamma, rgamma
See R doc. See wiki.
These functions are members of an object created by the Gamma
factory method. The factory method needs as optional argument an instance of one of the normal PRNG's.
Usage:
const libR = require('lib-r-math.js');
const {
Gamma,
rng: {
KnuthTAOCP2002,
normal: { AhrensDieter }
}
} = libR;
const defaultGamma = Gamma();
const mt = new KnuthTAOCP2002(123456);
const customG = Gamma(new AhrensDieter(mt));
const { dgamma, pgamma, qgamma, rgamma } = customG;
dgamma
The density function of the Gamma distribution. See R doc
$$ f(x)= \frac{1}{s^{a} \Gamma(a)} x^{a-1} e^{-x/s} $$
a
: shape parameters
: scale parameterx
: x >= 0
Alternative represention using shape parameter a
and rate parameter β
= $1/s$:
$$ f(x)= \frac{β^{a}}{\Gamma(a)} x^{a-1} e^{-xβ} $$
You must either specify scale
or rate
parameters but not both (unless rate = 1/scale).
typescript decl
declare function dgamma(
x: number | number[],
shape: number,
rate: number = 1,
scale: number = 1 / rate,
asLog: boolean = false
): number | number[];
x
: quantiles (scalar or array).shape
: shape parameter, must be positive.rate
: The rate parameter, when specified, leave scale
undefined (or set rate = 1/scale
). Must be strictly positive.scale
: The scale parameter, when specified, leave rate
undefined (or set scale = 1/rate
). Must be strictly positive.asLog
: if true, probabilities/densities p are returned as ln(p).
Usage:
const libR = require('lib-r-math.js');
const {
Gamma,
R: { numberPrecision, arrayrify }
} = libR;
const log = arrayrify(Math.log);
const seq = libR.R.seq()();
const precision = numberPrecision(9);
const { dgamma, pgamma, qgamma, rgamma } = Gamma();
const x = seq(0, 10, 2);
const d1 = dgamma( x, 1, 0.5);
precision(d1);
const d2 = dgamma(x, 2, 1/2);
precision(d2);
const d3 = dgamma(x, 5, 1);
precision(d3);
const d4 = dgamma( x, 7.5, 1, undefined, true);
precision(d4);
in R Console
dgamma( seq(0, 10, 2), 1, scale = 2);
dgamma( seq(0, 10, 2), 1, rate = 1/2);
dgamma( seq(0, 10, 2), 2, scale = 2);
dgamma( seq(0, 10, 2), 2, rate = 1/2);
dgamma( seq(0, 10, 2), 5, scale = 1);
dgamma( seq(0, 10, 2), 5, rate = 1);
dgamma( seq(0, 10, 2), 7.5, scale = 1, log = TRUE)
dgamma( seq(0, 10, 2), 7.5, rate = 1, log = TRUE)
pgamma
The cumulative probability function of the Gamma distribution. See R doc.
typescript decl
declare function pgamma(
x: number | number[],
shape: number,
rate: number = 1,
scale: number = 1 / rate,
lowerTail: boolean = true,
logP: boolean = false
): number | number[];
x
: quantiles (scalar or array).shape
: shape parameter, must be positive.rate
: The rate parameter, when specified, leave scale
undefined (or set rate = 1/scale
). Must be strictly positive.scale
: The scale parameter, when specified, leave rate
undefined (or set scale = 1/rate
). Must be strictly positive.lowerTail
: if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x].logP
: if true, probabilities/densities p are as ln(p).
Usage:
const libR = require('lib-r-math.js');
const {
Gamma,
R: { arrayrify, numberPrecision }
} = libR;
const log = arrayrify(Math.log);
const seq = libR.R.seq()();
const precision = numberPrecision(9);
const { dgamma, pgamma, qgamma, rgamma } = Gamma();
const x = seq(0, 10, 2);
const p1 = pgamma(x, 1, 0.5);
const p1Equavalent = pgamma(x, 1, undefined, 2);
precision(p1);
const p2 = pgamma(x, 2, 0.5);
const p2Equivalent = pgamma(x, 2, undefined, 2);
precision(p2);
const p3 = pgamma(x, 5, 1, undefined, false, true);
const p3Equivalent = pgamma(x, 5, undefined, 1, false, true);
precision(p3);
const p4 = pgamma(x, 7.5, 1, undefined, false, true);
const p4Equivalent = pgamma(x, 7.5, undefined, 1, false, true);
precision(p4);
Equivalent in R
x=seq(0,10,2);
pgamma(x, 1, rate = 0.5);
pgamma(x, 2, rate = 0.5);
pgamma(x, 5, rate=1, lower.tail = FALSE, log.p = TRUE);
pgamma(x, 7.5, rate = 7.5, lower.tail = FALSE , log.p = TRUE );
qgamma
The quantile function of the Gamma distribution. See R doc.
typescript decl
declare function pgamma(
x: number | number[],
shape: number,
rate: number = 1,
scale: number = 1 / rate,
lowerTail: boolean = true,
logP: boolean = false
): number | number[];
x
: quantiles (scalar or array).shape
: shape parameter, must be positive.rate
: The rate parameter, when specified, leave scale
undefined (or set rate = 1/scale
). Must be strictly positive.scale
: The scale parameter, when specified, leave rate
undefined (or set scale = 1/rate
). Must be strictly positive.lowerTail
: if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x].logP
: if true, probabilities/densities p are as ln(p).
Usage:
const libR = require('lib-r-math.js');
const {
Gamma,
R: { numberPrecision, arrayrify }
} = libR;
const log = arrayrify(Math.log);
const seq = libR.R.seq()();
const precision = numberPrecision(9);
const { dgamma, pgamma, qgamma, rgamma } = Gamma();
const x = seq(0, 10, 2);
const pp1 = pgamma(x, 1, 0.5);
const q1 = qgamma(pp1, 1, 0.5);
precision(q1);
const pp2 = pgamma(x, 2, 0.5);
const q2 = qgamma(pp2, 2, 0.5);
precision(q2);
const pp3 = pgamma(x, 5, 1, undefined, false, true);
const q3 = qgamma(pp3, 5, undefined, 1, false, true);
precision(q3);
const pp4 = pgamma(x, 7.5, 1, undefined, false);
const q4 = qgamma(log(pp4), 7.5, 1, undefined, false, true);
precision(q4);
Equivalent in R
x = seq(0, 10, 2);
pp1 = pgamma(x, 1, 0.5)
qgamma(pp1, 1, 0.5)
pp2 = pgamma(x, 2, 0.5);
qgamma(pp2, 2, 0.5);
pp3 = pgamma(x, 5, 1, lower.tail= FALSE, log.p=TRUE);
qgamma(pp3, 5, scale= 1, lower.tail=FALSE, log.p=TRUE);
pp4 = pgamma(x, 7.5, 1, lower.tail=FALSE);
qgamma(log(pp4), 7.5, 1, lower.tail=FALSE , log.p=TRUE);
rgamma
Generates random deviates for the Gamma distribution. See R doc.
declare function rgamma(
n: number,
shape: number,
rate: number = 1,
scale: number = 1 / rate
): number | number[];
n
: number of deviates generated.shape
: shape parameter, must be positive.rate
: The rate parameter, when specified, leave scale
undefined (or set rate = 1/scale
). Must be strictly positive.scale
: The scale parameter, when specified, leave rate
undefined (or set scale = 1/rate
). Must be strictly positive.
Usage:
const libR = require('lib-r-math.js');
const {
Gamma,
rng: {
LecuyerCMRG,
normal: { BoxMuller }
},
R: { arrayrify, numberPrecision }
} = libR;
const log = arrayrify(Math.log);
const seq = libR.R.seq()();
const precision = numberPrecision(9);
const lc = new LecuyerCMRG(1234);
const { dgamma, pgamma, qgamma, rgamma } = Gamma(new BoxMuller(lc));
const r1 = rgamma(5, 1, 0.5);
precision(r1);
const r2 = rgamma(5, 2, 0.5);
precision(r2);
const r3 = rgamma(5, 7.5, 1);
precision(r3);
Equivalent in R
RNGkind("L'Ecuyer-CMRG", normal.kind="Box-Muller")
set.seed(1234);
rgamma(5, 1, 0.5);
rgamma(5, 2, 0.5);
rgamma(5, 7.5, 1);
Geometric distribution
dgeom, qgeom, pgeom, rgeom
See R doc and wiki.
These functions are properties of an object created by the Geometric
factory method. The factory method needs as optional argument an instance of one of the normal PRNG's.
Usage:
const libR = require('lib-r-math.js');
const {
Geometric,
rng: {
SuperDuper,
normal: { BoxMuller }
}
} = libR;
const defaultG = Geometric();
const sd = new SuperDuper(3456);
const explicitG = Geometric(new BoxMuller(mt));
const { dgeom, pgeom, qgeom, rgeom } = explicitG;
dgeom
The density function of the Geometric distribution. See R doc.
$$ \large p(x) = p (1-p)^{x} $$
typescript decl
declare function dgeom(
x: number | number[],
prob: number,
asLog: boolean = false
): number | number[];
x
: quantiles (array or scalar).prob
: probability of success in each trial. 0 < prob <= 1.asLog
: if TRUE, probabilities p are given as ln(p).
Usage:
const libR = require('lib-r-math.js');
const {
Geometric,
R: { numberPrecision }
} = libR;
const seq = libR.R.seq()();
const precision = numberPrecision(9);
const { dgeom, pgeom, qgeom, rgeom } = Geometric();
const x = seq(0,4);
const d1 = dgeom(x, 0.5);
precision(d1);
const d2 = dgeom(x, 0.2, true);
precision(d2);
Equivalent in R
x = seq(0,4);
> dgeom(x, 0.5)
[1] 0.50000 0.25000 0.12500 0.06250 0.03125
> dgeom(x, 0.2, TRUE)
[1] -1.609438 -1.832581 -2.055725 -2.278869 -2.502012
pgeom
The distribution function of the Geometric distribution. See R doc.
typescript decl
declare function pgeom(
q: number | number[],
prob: number,
lowerTail: boolean = true,
logP: boolean = false
): number | number[];
q
: the number of failures before success.prob
: probability of success.lowerTail
: if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x].logP
: if TRUE, probabilities p are given as ln(p).
const libR = require('lib-r-math.js');
const {
Geometric,
R: { numberPrecision }
} = libR;
const seq = libR.R.seq()();
const precision = numberPrecision(9);
const { dgeom, pgeom, qgeom, rgeom } = Geometric();
const q = seq(5, 9);
const p1 = pgeom(q, 0.1);
precision(p1);
const p2 = pgeom(q, 0.1, false);
precision(p2);
const p3 = pgeom(q, 0.2, false, true);
precision(p3);
Equivalent in R
q=seq(5, 9);
pgeom(q, 0.1);
pgeom(q, 0.1, FALSE)
pgeom(q, 0.2, FALSE, TRUE)
qgeom
The quantile function of the Geometric distribution. See R doc.
typescript decl
declare function qgeom(
p: number | number[],
prob: number,
lowerTail: boolean = true,
logP: boolean = false
): number | number[];
p
: probabilities (scalar or array).prob
: probability of success.lowerTail
: if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x].logP
: if TRUE, probabilities p are given as ln(p).
Usage:
const libR = require('lib-r-math.js');
const {
Geometric,
R:{ numberPrecision }
} = libR;
const seq = libR.R.seq()();
const precision = numberPrecision(9);
const { dgeom, pgeom, qgeom, rgeom } = Geometric();
const q = seq(5, 9);
const pp1 = pgeom(q, 0.2, false, true);
const q1 = qgeom(pp1, 0.2, false, true);
precision(q1);
const pp2 = pgeom(q, 0.9, true, true);
const q2 = qgeom(pp2, 0.9, true, true);
precision(q2);
const pp3 = pgeom([...q, Infinity], 0.5);
const q3 = qgeom(pp3, 0.5);
precision(q3);
Equivalent in R
q = seq(5, 9);
pp1 = pgeom(q, 0.2, FALSE, TRUE)
qgeom(pp1, 0.2, FALSE, TRUE)
pp2 = pgeom(q, 0.9, TRUE, TRUE);
qgeom(pp2, 0.9, TRUE, TRUE);
pp3 = pgeom(c(q, Inf), 0.5);
qgeom(pp3, 0.5);
rgeom
Generates random deviates for the Geometric distribution. See R doc.
typescript decl
declare function rgeom(
n: number,
prob: number
): number | number[];
n
: number of deviates to generate.prob
: probability of success.
Usage:
const libR = require('lib-r-math.js');
const {
Geometric,
rng: {
KnuthTAOCP,
normal: { KindermanRamage }
},
R: { arrayrify, numberPrecision, seq: seqCR }
} = libR;
const log = arrayrify(Math.log);
const seq = seqCR()();
const precision = numberPrecision(9);
const k97 = new KnuthTAOCP(1234);
const { dgeom, pgeom, qgeom, rgeom } = Geometric(new KindermanRamage(mt));
k97.init(3456);
rgeom(5, 0.001);
k97.init(9876);
rgeom(5, 0.999);
k97.init(934);
rgeom(10, 0.4);
in R Console
RNGkind("Mersenne-Twister", normal.kind = "Inversion");
> set.seed(3456)
> rgeom(5, 0.001)
[1] 573 1153 75 82 392
> set.seed(9876)
> rgeom(5, 0.999);
[1] 0 0 0 0 0
> set.seed(934)
> rgeom(10, 0.4);
[1] 1 2 6 1 0 1 0 0 1 2
Hypergeometric distribution
dhyper, qhyper, phyper, rhyper
See R doc and wiki.
These functions are properties of an object created by the HyperGeometric
factory method. The factory method needs as optional argument an instance of one of the uniform random PRNG's classes.
Usage:
const libR = require('lib-r-math.js');
const {
HyperGeometric,
rng: { MersenneTwister, SuperDuper }
} = libR;
const log = libR.R.arrayrify(Math.log);
const seq = libR.R.seq()();
const precision = libR.R.numberPrecision(9);
const sd = new SuperDuper(1234);
const hyperG = HyperGeometric(sd);
const default = HyperGeometric();
const { dhyper, phyper, qhyper, rhyper } = default;
dhyper
The density function of the Hypergeometric distribution. See R doc and wiki.
$$ \large p(X = x) = \frac{choose(m, x) choose(n, k-x)}{choose(m+n, k)} $$
typescript decl
declare function dhyper(
x: number | number[],
m: number,
n: number,
k: number,
aslog: boolean = false
): number | number[];
Where:
x
: is the number of observed successes.m
: is the number of success states in the populationn
: is the number of failure states in the populationk
: is the number of draws from the population (n+m) sample.
Usage:
const libR = require('lib-r-math.js');
const { HyperGeometric } = libR;
const log = libR.R.arrayrify(Math.log);
const seq = libR.R.seq()();
const precision = libR.R.numberPrecision(9);
const { dhyper, phyper, qhyper, rhyper } = HyperGeometric();
const d1 = dhyper(
seq(0, 4),
5,
3,
5,
false
);
precision(d1);
const d2 = dhyper(
seq(0, 4),
3,
4,
7
);
precision(d2);
const d3 = dhyper(
seq(0, 3),
3,
4,
5
);
precision(d3);
const d4 = dhyper(
seq(0, 3),
3,
9,
5
);
precision(d4);
in R Console
> dhyper( seq(0, 4), 5, 3, 5, FALSE );
[1] 0.0000000 0.0000000 0.1785714 0.5357143 0.2678571
> dhyper( seq(0, 4), 3, 4, 7 );
[1] 0 0 0 1 0
> dhyper( seq(0, 3), 3, 4, 5);
[1] 0.0000000 0.1428571 0.5714286 0.2857143
> dhyper( seq(0, 3),
3,
9,
5
);
[1] 0.15909091 0.47727273 0.31818182 0.04545455
phyper
The distribution function of the Hypergeometric distribution. See R doc and wiki.
typescript decl
declare function phyper(
q: number | number[],
m: number,
n: number,
k: number,
lowerTail: boolean = true,
logP: boolean = false
): number | number[];
q
: is the number of observed successes.m
: is the number of success states in the populationn
: is the number of failure states in the populationk
: is the number of draws from the population (n+m) sample.lowerTail
: if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x].logP
: if TRUE, probabilities p are given as ln(p).
Usage:
const libR = require('lib-r-math.js');
const { HyperGeometric } = libR;
const log = libR.R.arrayrify(Math.log);
const seq = libR.R.seq()();
const precision = libR.R.numberPrecision(9);
const { dhyper, phyper, qhyper, rhyper } = HyperGeometric();
const p1 = phyper(
seq(2, 5),
5,
3,
5
);
precision(p1);
const p2 = phyper(
seq(2, 6),
9,
18,
9,
false
);
precision(p2);
const p3 = phyper(
seq(2, 6),
9,
18,
6,
false,
true
);
precision(p3);
Equivalent in R Console
> phyper( seq(2, 5), 5, 3, 5 );
[1] 0.1785714 0.7142857 0.9821429 1.0000000
> phyper( seq(2, 6), 9, 18, 9, FALSE);
[1] 0.661155260 0.328440469 0.098099460 0.015834814 0.001209988
> phyper( seq(2, 6), 9, 18, 6, FALSE, TRUE);
[1] -1.188652 -2.616312 -4.835127 -8.167332 -Inf
qhyper
The quantile function of the Hypergeometric distribution. See R doc and wiki.
typescript decl
declare function qhyper(
p: number | number[],
m: number,
n: number,
k: number,
lowerTail: boolean = true,
logP: boolean = false
): number | number[];
p
: is probability of observed successes.m
: is the number of success states in the populationn
: is the number of failure states in the populationk
: is the number of draws from the population (n+m) sample.lowerTail
: if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x].logP
: if TRUE, probabilities p are given as ln(p).
Usage:
const libR = require('lib-r-math.js');
const { HyperGeometric } = libR;
const log = libR.R.arrayrify(Math.log);
const seq = libR.R.seq()();
const precision = libR.R.numberPrecision(9);
const { dhyper, phyper, qhyper, rhyper } = HyperGeometric();
const q1 = qhyper(
seq(0, 1, 0.2),
5,
2,
3
);
precision(q1);
const q2 = qhyper(
log(seq(0, 1, 0.2)),
5,
2,
3,
false,
true
);
precision(q2);
const q3 = qhyper(
seq(0, 1, 0.2),
50,
20,
6
);
precision(q3);
Equivalent in R Console
>qhyper( seq(0, 1, 0.2), 5,2,3 );
[1] 1 2 2 2 3 3
>qhyper( log(seq(0, 1, 0.2)), 5, 2, 3, FALSE, TRUE);
[1] NaN 3 2 2 2 1
>qhyper( seq(0, 1, 0.2),50,20,6 );
[1] 0 3 4 5 5 6
rhyper
Generates random deviates for the Hypergeometric distribution. See R doc and wiki.
typescript decl
declare function rhyper(
N: number,
m: number,
n: number,
k: number
): number | number[];
N
: number of deviates to generate.m
: is the number of success states in the populationn
: is the number of failure states in the populationk
: is the number of draws from the total population (n+m) sample.
Usage:
const libR = require('lib-r-math.js');
const { HyperGeometric, rng: { MersenneTwister } } = libR;
const log = libR.R.arrayrify(Math.log);
const seq = libR.R.seq()();
const precision = libR.R.numberPrecision(9);
const mt = new MersenneTwister(1234);
const hyperG = HyperGeometric(mt);
const { dhyper, phyper, qhyper, rhyper } = hyperG;
mt.init(1234);
rhyper(5, 4, 3, 5);
mt.init(9876);
rhyper(5, 40, 19, 13);
mt.init(5688);
rhyper(5, 40, 99, 33);
Equivalent in R Console
RNGkind("Mersenne-Twister", normal.kind="Inversion")
>set.seed(1234);
>rhyper(5, 4, 3, 5);
[1] 2 3 3 3 4
>set.seed(9876);
>rhyper(5, 40, 19, 13);
[1] 7 9 11 9 9
> set.seed(5688);
> rhyper(5, 40, 99, 33);
[1] 12 10 10 7 12
Logistic distribution
dlogis, qlogis, plogis, rlogis
See R doc and wiki.
These functions are properties of an object created by the Logistic
factory method. The factory method needs as optional argument an instance of one of the uniform random PRNG's classes.
Usage:
const libR = require('lib-r-math.js');
const { Logistic, rng: { MersenneTwister, SuperDuper } } = libR;
const log = libR.R.arrayrify(Math.log);
const seq = libR.R.seq()();
const precision = libR.R.numberPrecision(9);
const sd = new SuperDuper(1234);
const customL = Logistic(sd);
const defaultL = Logistic();
const { dlogis, plogis, qlogis, rlogis } = defaultL;
dlogis
The density function of the Logistic distribution with location = m
and scale = s
has density function.
$$ f(x) = \large \frac{e^{-\frac{x-m}{s}}}{s \left( 1 + e^{-\frac{x-m}{s}} \right)^{2}} $$
See R doc.
typescript decl
declare function dlogis(
x: number | number[],
location: number = 0,
scale: number = 1,
asLog: boolean = false
): number | number[];
x
: quantiles (scalar or array).location
: location parameter of the Logistic distributionscale
: the scale parameter of the Logistic distribution. Strictly positive.asLog
: if TRUE, probabilities p are given as ln(p).
Usage:
const libR = require('lib-r-math.js');
const { Logistic } = libR;
const log = libR.R.arrayrify(Math.log);
const seq = libR.R.seq()();
const precision = libR.R.numberPrecision(9);
const { dlogis, plogis, qlogis, rlogis } = Logistic();
const x = [-Infinity, ...seq(-10, 10, 2.5), Infinity];
const d1 = dlogis(x, 5, 2);
precision(d1);
const d2 = dlogis(x, 0, 2, true);
precision(d2);
const d3 = dlogis(x, -9, 2);
precision(d3);
Equivalent in R Console
> x = c(-Inf, seq(-10,10,2.5), Inf);
> dlogis(x, 5, 2);
[1] 0.0000000000 0.0002762365 0.0009615112 0.0033240283 0.0112247052
[6] 0.0350518583 0.0865523935 0.1250000000 0.0865523935 0.0350518583
[11] 0.0000000000
> dlogis(x, 0, 2, TRUE);
[1] -Inf -5.706578 -4.489638 -3.350927 -2.447005 -2.079442 -2.447005
[8] -3.350927 -4.489638 -5.706578 -Inf
> dlogis(x, -5, 2);
[1] 0.0000000000 0.0350518583 0.0865523935 0.1250000000 0.0865523935
[6] 0.0350518583 0.0112247052 0.0033240283 0.0009615112 0.0002762365
[11] 0.0000000000
plogis
The distribution function of the Logistic distribution. See R doc.
typescript decl
declare function plogis(
q: number | number[],
location: number = 0,
scale: number = 1,
lowerTail: boolean = true,
logP: boolean = false
): number | number[];
q
: quantiles (scalar or array).location
: location parameter of the Logistic distributionscale
: the scale parameter of the Logistic distribution. Strictly positive.lowerTail
: if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x].logP
: if TRUE, probabilities p are given as ln(p).
Usage:
const libR = require('lib-r-math.js');
const { Logistic } = libR;
const log = libR.R.arrayrify(Math.log);
const seq = libR.R.seq()();
const precision = libR.R.numberPrecision(9);
const { dlogis, plogis, qlogis, rlogis } = Logistic();
const x = [-Infinity, ...seq(-10, 10, 2.5), Infinity];
const p1 = plogis(x, 5, 2);
precision(p1);
const p2 = plogis(x, 0, 2, true, true);
precision(p2);
const p3 = plogis(x, -9, 2, false);
precision(p3);
Equivalent in R Console
> x = c(-Inf, seq(-10,10,2.5), Inf);
> plogis(x, 5, 2);
[1] 0.0000000000 0.0005527786 0.0019267347 0.0066928509 0.0229773699
[6] 0.0758581800 0.2227001388 0.5000000000 0.7772998612 0.9241418200
[11] 1.0000000000
> plogis(x, 0, 2, TRUE, TRUE);
[1] -Inf -5.006715348 -3.773245464 -2.578889734 -1.501929081
[6] -0.693147181 -0.251929081 -0.078889734 -0.023245464 -0.006715348
[11] 0.000000000
plogis(x, -9, 2, FALSE);
[1] 1.000000e+00 6.224593e-01 3.208213e-01 1.192029e-01 3.732689e-02
[6] 1.098694e-02 3.172683e-03 9.110512e-04 2.611903e-04 7.484623e-05
[11] 0.000000e+00
qlogis
The quantile function of the Logistic distribution. See R doc.
typescript decl
declare function qlogis(
p: number | number[],
location: number = 0,
scale: number = 1,
lowerTail: boolean = true,
logP: boolean = false
): number | number[];
p
: probabilities (scalar or array). 0 ≤ p ≤ 1.location
: location parameter of the Logistic distributionscale
: the scale parameter of the Logistic distribution. Strictly positive.lowerTail
: if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x].logP
: if TRUE, probabilities p are given as ln(p).
Usage:
const libR = require('lib-r-math.js');
const { Logistic } = libR;
const log = libR.R.arrayrify(Math.log);
const seq = libR.R.seq()();
const precision = libR.R.numberPrecision(9);
const { dlogis, plogis, qlogis, rlogis } = Logistic();
const x = [-Infinity, ...seq(-10, 10, 2.5), Infinity];
const pp1 = plogis(x, 5, 2);
const q1 = qlogis(pp1, 5, 2);
precision(q1);
const pp2 = plogis(x, 0, 2);
const q2 = qlogis(log(pp2), 0, 2, true, true);
precision(q2);
const pp3 = plogis(x, -9, 2, false);
const q3 = qlogis(pp3, -9, 2, false);
precision(q3);
Equivalent in R
> x = c(-Inf, seq(-10,10,2.5), Inf);
> pp1 = plogis(x, 5, 2);
> qlogis(pp1, 5, 2);
[1] -Inf -10.0 -7.5 -5.0 -2.5 0.0 2.5 5.0 7.5 10.0 Inf
> pp2 = plogis(x, 0, 2);
> qlogis(log(pp2), 0, 2, TRUE, TRUE);
[1] -Inf -10.0 -7.5 -5.0 -2.5 0.0 2.5 5.0 7.5 10.0 Inf
> pp3 = plogis(x, -9, 2, FALSE);
> qlogis(pp3, -9, 2, FALSE);
[1] -Inf -10.0 -7.5 -5.0 -2.5 0.0 2.5 5.0 7.5 10.0 Inf
rlogis
Generates random deviates for the Logistic distribution. See R doc.
typescript decl
declare function rlogis(
N: number,
location: number = 0,
scale: number = 1
): number | number[];
Usage:
const libR = require('lib-r-math.js');
const { Logistic, rng: { MersenneTwister } } = libR;
const log = libR.R.arrayrify(Math.log);
const seq = libR.R.seq()();
const precision = libR.R.numberPrecision(9);
const mt = new MersenneTwister(5321);
const { dlogis, plogis, qlogis, rlogis } = Logistic(mt);
const r1 = rlogis(5, 5, 2);
precision(r1);
const r2 = rlogis(5, 0, 0.2);
precision(r2);
const r3 = rlogis(5, -9, 4);
precision(r3);
> RNGkind("Mersenne-Twister", normal.kind="Inversion");
> set.seed(5321)
> rlogis(5, 5, 2)
[1] 7.024470 6.840195 6.770020 4.015303 1.673623
> rlogis(5, 0, 0.2)
[1] 0.20239877 0.25232485 -0.05065645 -0.48847358 0.17076147
> rlogis(5, -9, 4)
[1] 10.3948377 -14.9312628 -8.1271896 -14.0656700 -0.6090719
Log Normal distribution
See R doc.
from wiki:
In probability theory, a log-normal (or lognormal) distribution is a continuous probability distribution of a random variable whose logarithm is normally distributed. Thus, if the random variable X is log-normally distributed, then Y = ln(X) has a normal distribution. Likewise, if Y has a normal distribution, then the exponential function of Y, X = exp(Y), has a log-normal distribution. A random variable which is log-normally distributed takes only positive real values.
dlnorm, qlnorm, plnorm, rlnorm
These functions are properties of an object created by the LogNormal
factory method. The factory method needs the result returned by the Normal factory method. Various instantiation methods are given as an example.
Usage:
const libR = require('lib-r-math.js');
const {
Normal,
LogNormal,
rng: { MersenneTwister },
rng: { normal: { Inversion } }
} = libR;
const log = libR.R.arrayrify(Math.log);
const seq = libR.R.seq()();
const precision = libR.R.numberPrecision(9);
const mt = new MersenneTwister(5321);
const customL = LogNormal(Normal(new Inversion(mt)));
const defaultL = LogNormal();
const { dlnorm, plnorm, qlnorm, rlnorm } = customL;
dlnorm
The density function of the Log Normal distribution. See R doc.
$$ f(x) = \frac{1}{x} \cdot \frac{1}{\sigma \cdot \sqrt{2 \pi}} exp \left( -\frac{(ln(x) - \mu)^{2}}{2 \cdot \sigma^{2} } \right) $$
Note: deviate x
has a normal distribution with mean $\mu$ and standard deviation $\sigma$.
typescript decl
declare function dlnorm(
x: number | number[],
meanLog: number = 0,
sdLog: number = 1,
asLog: boolean = false
): number | number[];
x
: quantiles, with distribution $x ~ N(\mu, \sigma)$meanLog
: the mean of the normally distributed x
sdLog
: the standard deviation ($\sigma$) of the normal distributed x
.asLog
: return the densities as ln(p).
Usage:
const libR = require('lib-r-math.js');
const { LogNormal } = libR;
const log = libR.R.arrayrify(Math.log);
const seq = libR.R.seq()();
const precision = libR.R.numberPrecision(9);
const { dlnorm, plnorm, qlnorm, rlnorm } = LogNormal();
const x = seq(0, 3, 0.5);
const d1 = dlnorm(x, 0, 0.25);
precision(d1);
const d2 = dlnorm(x, 0, 0.5, true);
precision(d2);
const d3 = dlnorm(x, 0, 1);
precision(d3);
Equivalent in R
x = seq(0,3,0.5)
options(scipen=999)
options(digits=9)
dlnorm(x, 0, 0.25)
dlnorm(x, 0, 0.5, TRUE);
dlnorm(x, 0, 1);
plnorm
The distribution function of the Log Normal distribution. See R doc.
$$ f(x) = \frac{1}{2} + \frac{1}{2} \cdot erf \left( \frac{(ln(x)-\mu)}{\sigma \cdot \sqrt{2}} \right) $$
Note: deviate x
has a normal distribution with mean $\mu$ and standard deviation $\sigma$.
typescript decl
declare function plnorm(
q: number | number[],
meanLog: number = 0,
sdLog: number = 1,
lowerTail: boolean = true,
logP: boolean = false
): number | number[];
q
: quantiles, with distribution $x ~ N(\mu, \sigma)$meanLog
: the mean of the normally distributed x
sdLog
: the standard deviation ($\sigma$) of the normal distributed x
.lowerTail
: if TRUE (default), probabilities are P[X <= x], otherwise, P[X > x].logP
: if TRUE, probabilities p are given as ln(p).
Usage:
const libR = require('lib-r-math.js');
const { LogNormal } = libR;
const log = libR.R.arrayrify(Math.log);
const seq = libR.R.seq()();
const precision = libR.R.numberPrecision(9);
const { dlnorm, plnorm, qlnorm, rlnorm } = LogNormal();
const x = seq(0, 3, 0.5);
const p1 = plnorm(x, 0, 0.25);
precision(p1);
const p2 = plnorm(x, 0, 0.5, true);
precision(p2);
const p3 = plnorm(x, 0, 1);
precision(p3);
Equivalent in R
> x = seq(0,3,0.5)
> options(scipen=999)
> options(digits=9)
> plnorm(x, 0, 0.25);
[1] 0.00000000000 0.00278061786 0.50000000000 0.94758338236 0.99721938214
[6] 0.99987640941 0.99999444730
> plnorm(x, 0, 0.5, TRUE);
[1] 0.000000000 0.082828519 0.500000000 0.791297127 0.917171481 0.966567582
[7] 0.985997794
> plnorm(x, 0, 1);
[1] 0.000000000 0.244108596 0.500000000 0.657432169 0.755891404 0.820242786
[7] 0.864031392
qlnorm
The quantile function of the Log Normal distribution. See R doc.
typescript decl
declare function qlnorm(
p: number | number[],
meanLog: number = 0,
sdLog: number = 1,
lowerTail: boolean = true,
logP: boolean = false
): number | number[];
p
: probabilities.meanLog
: the mean of the normally distributed x
sdLog
: the standard deviation ($\sigma$) of the normal distributed x
.lowerTail
: if TRUE (default), probabilities are P[X <= x], otherwise, P[X > x].logP
: if TRUE, probabilities p are given as ln(p).
Usage:
const libR = require('lib-r-math.js');
const { LogNormal } = libR;
const log = libR.R.arrayrify(Math.log);
const seq = libR.R.seq()();
const precision = libR.R.numberPrecision(9);
const { dlnorm, plnorm, qlnorm, rlnorm } = LogNormal();
const x = seq(0, 3, 0.5);
const pp1 = plnorm(x, 0, 0.25);
const q1 = qlnorm(pp1, 0, 0.25);
precision(q1);
const pp2 = plnorm(x, 2, 0.5, false, true);
const q2 = qlnorm(pp2, 2, 0.5, false, true);
precision(q2);
const pp3 = plnorm(x);
const q3 = qlnorm(pp3);
precision(q3);
Equivalent in R
> x = seq(0,3,0.5)
> options(scipen=999)
> options(digits=9)
pp1 = plnorm(x, 0, 0.25);
qlnorm(pp1, 0, 0.25);
[1] 0.0 0.5 1.0 1.5 2.0 2.5 3.0
pp2 = plnorm(x, 2, 0.5, FALSE, TRUE);
qlnorm(pp2, 2, 0.5, FALSE, TRUE);
[1] 0.0 0.5 1.0 1.5 2.0 2.5 3.0
> pp3 = plnorm(x);
> qlnorm(pp3);
[1] 0.0 0.5 1.0 1.5 2.0 2.5 3.0
rlnorm
Generates random deviates from the Log Normal distribution. See R doc.
typescript decl
declare function rlnorm(
n: number,
meanlog: number = 0,
sdlog: number = 1
): number | number[];
Usage:
const libR = require('lib-r-math.js');
const {
Normal,
LogNormal,
rng: { MersenneTwister },
rng: { normal: { Inversion } }
} = libR;
const precision = libR.R.numberPrecision(9);
const mt = new MersenneTwister(0);
const lNorm = LogNormal(Normal(new Inversion(mt)));
const { dlnorm, plnorm, qlnorm, rlnorm } = lNorm;
mt.init(12345);
const r1 = rlnorm(5);
precision(r1);
mt.init(56789);
const r2 = rlnorm(5, 2, 0.3);
precision(r2);
mt.init(332211);
const r3 = rlnorm(5, 2, 3.2);
precision(r3);
Equivalent in R
> options(scipen=999)
> options(digits=9)
> RNGkind("Mersenne-Twister", normal.kind="Inversion")
> set.seed(12345)
> rlnorm(5)
[1] 1.795940460 2.032905433 0.896458467 0.635402150 1.832878086
> set.seed(56789)
> rlnorm(5,2,0.3)
[1] 10.16535485 7.83173724 6.60669182 11.81655477 6.05586400
> set.seed(332211)
> rlnorm(5,2,3.2)
[1] 1069.701128375 1.509608802 10.874497520 0.115348102 562.383238202
Multinomial distribution
See R doc:
from wiki:
dmultinom, rmultinom
These functions are properties of an object created by the Multinomial
factory method. The factory method needs as optional argument an instance of one of the uniform random PRNG's classes.
Note: Analog pmultinom, qmultinom
are not implemented in R and hence not available in this port. In Future implementation for pmultinom
would require an analog for $P(\vec{X} \leq \vec{x})$ by constraining the multivariate vector X
to a hyperplane $\vec{n} \cdot \vec{X} = d$ where d
is the total number of draws and $\vec{n}$ is the N dimensional hyperplane vector normal $\vec{n}=(1,1,...,1)$. Elements of $\vec{X}$ have only integer values. This is potentially an expensive operation. We would need to sum over
$$\frac{(size+k)!}{k!\cdot((size+k)-k)!}$$
probability mass
values, were $k$ is the dimension of vector:$\vec{x}$ and $size = \sum*{i=1}^{k} x*{i}$.
Usage:
const libR = require('lib-r-math.js');
const { MultiNomial, rng: { MersenneTwister, SuperDuper } } = libR;
const log = libR.R.arrayrify(Math.log);
const seq = libR.R.seq()();
const precision = libR.R.numberPrecision(9);
const sd = new SuperDuper(1234);
const customM = MultiNomial(sd);
const defaultM = MultiNomial();
const { dmultinom, rmultinom } = defaultM;
dmultinom
The probability mass function
of the multinomial distribution. See wiki or R doc
$$ f( x*{1} , ... , x*{k}; p*{1},...,p*{k}) = \frac{n!}{x*{1}!\cdot\cdot\cdot x*{k}!} p*{1}^{x*{1}} \times\cdot\cdot\cdot\times p*{k}^{x*{k}}, when \sum*{i=1}^{k} x*{i} = n $$
typescript decl
declare interface IdmultinomOptions {
x: number[];
prob: number[];
size?: number;
asLog?: boolean;
}
declare function dmultinom(option: IdmultinomOptions): number[];
dmultinom
needs as input an JS object (typescript interface type IdmultinomOptions
) with the following properties:
x
: array of quantiles (minimal item count is 2)prob
: array of corresponding non-zero probabilities corresponding with the quantiles.size
: optional, you can safely omit it, functions as a kind of checksum: size = $\sum*{i=1}^{k} x*{i}$asLog
: probabilities are returned as ln(p).
Usage:
const libR = require('lib-r-math.js');
const { Multinomial } = libR;
const precision = libR.R.numberPrecision(9);
const { dmultinom, rmultinom } = Multinomial();
const d1 = dmultinom({
x: [3, 5],
prob: [0.25, 0.75]
});
precision(d1);
const d2 = dmultinom({
x: [3, 5, 9],
prob: [0.2, 0.7, 0.1]
});
precision(d2);
const d3 = dmultinom({
x: [3, 5, 9, 4],
prob: [2, 8, 4, 6],
asLog: true
});
precision(d3);
Equivalent in R console
> options(scipen=999)
> options(digits=9)
> dmultinom(x=c(3, 5), prob=c(0.25, 0.75));
[1] 0.2076416
> dmultinom(x=c(3, 5, 9), prob=c(0.2, 0.7, 0.1));
[1] 0.0000018304302
> dmultinom(x=c(3,5,9,4), prob=c(2,8,4,6), log=TRUE)
[1] -7.96903499
rmultinom
Generates deviates ( these are arrays of arrays ) of the multinomial distribution.
typescript decl
declare function rmultinom(
n: number,
size: number,
prob: number | number[]
): (number[]) | (number[][]);
n
: returns an array of size n
nested arrays of dimension prob.length
.size
: distribute size elements amongst prob.length
bins for each deviate.prob
: an array (in case of a scalar or array of length 1) describing the probabilities for success for ech bin.@return
: returns n
arrays each of length k = (prob.length)
.
Usage:
const libR = require('lib-r-math.js');
const {
Multinomial,
rng: { MersenneTwister },
rng: { normal: { Inversion } },
R: { sum, div, mult }
} = libR;
const log = libR.R.arrayrify(Math.log);
const seq = libR.R.seq()();
const precision = libR.R.numberPrecision(9);
const mt = new MersenneTwister();
const { dmultinom, rmultinom } = Multinomial(mt);
const prob1a = [167, 500, 167, 167];
const prob1b = div(prob1a, sum(prob1a));
mt.init(1234);
rmultinom(4, 40, prob1b);
mt.init(1234);
rmultinom(4, 40, prob1a);
const prob2a = [10, 30, 40, 90];
const prob2b = div(prob2a, sum(prob2a));
mt.init(5678);
rmultinom(4, 5299, prob2b);
mt.init(5678);
rmultinom(4, 5299, prob2a);
const prob3a = [9, 8, 0, 6, 0, 2];
const prob3b = div(prob3a, sum(prob3a));
mt.init(666);
rmultinom(4, 9967, prob3b);
mt.init(666);
rmultinom(4, 9967, prob3a);
Equivalent in R
> RNGkind("Mersenne-Twister")
> prob1a=c(167,500,167,167)
> set.seed(1234);
> t(rmultinom(4, 40, prob1a))
[,1] [,2] [,3] [,4]
[1,] 4 21 8 7
[2,] 7 17 9 7
[3,] 2 25 7 6
[4,] 7 18 8 7
> prob2a=c(10, 30, 40, 90)
> set.seed(5678)
> t(rmultinom(4, 5299, prob2a))
[,1] [,2] [,3] [,4]
[1,] 316 945 1271 2767
[2,] 308 896 1206 2889
[3,] 329 871 1292 2807
[4,] 308 930 1265 2796
> prob3a=c(9, 8, 0, 6, 0, 2)
> set.seed(666)
> t(rmultinom(4, 9967, prob3a));
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 3727 3098 0 2299 0 843
[2,] 3563 3142 0 2447 0 815
[3,] 3534 3145 0 2455 0 833
[4,] 3702 3125 0 2365 0 775
Poisson distribution
dpois, qpois, ppois, rpois
See R doc and wiki.
These functions are properties of an object created by the Poisson
factory method. The factory method needs as optional argument an instance of one of the normal random PRNG's classes.
Usage:
const libR = require('lib-r-math.js');
const { Poisson, rng: { SuperDuper }, rng: { normal: { BoxMuller } } } = libR;
const defaultP = Poisson();
const sd = new SuperDuper(123);
const explicitP = Poisson(new BoxMuller(sd));
const { dpois, ppois, qpois, rpois } = explicitP;
dpois
The probability mass function
of the Poisson distribution. See R doc.
$$ p(x) = \frac{λ^{x}}{x!} \cdot e^{-λ} $$
typescript decl
declare function dpois(
x: number | number[],
lambda: number,
asLog: boolean = false
): number | number[];
x
: quantile(s). Scalar or array.lambda
: the lambda λ
parameter from the Poisson distribution.asLog
: if TRUE, probabilities p are given as ln(p).
Usage:
const libR = require('lib-r-math.js');
const { Poisson } = libR;
const seq = libR.R.seq()();
const precision = libR.R.numberPrecision(9);
const { dpois, ppois, qpois, rpois } = Poisson();
const x = seq(0, 10, 2);
const d1 = dpois(x, 1, true);
precision(d1);
const d2 = dpois(x, 4);
precision(d2);
const d3 = dpois(x, 10);
precision(d3);
Equivalent in R
options(scipen=999)
options(digits=9)
x = seq(0,10,2);
dpois(x, 1, TRUE);
[1] -1.000000 -1.693147 -4.178054 -7.579251 -11.604603 -16.104413
dpois(x, 4);
[1] 0.018315639 0.146525111 0.195366815 0.104195635 0.029770181 0.005292477
dpois(x, 10);
[1] 0.0000453999298 0.0022699964881 0.0189166374010 0.0630554580035
[5] 0.1125990321490 0.1251100357211
ppois
The cumulative distribution function of the Poisson distribution. See R doc.
typescript decl
declare function ppois(
q: number | number[],
lambda: number,
lowerTail: boolean = true,
logP: boolean = false
): number | number[];
q
: quantile(s). A Scalar or array.lambda
: the lambda λ
parameter from the Poisson distribution.lowerTail
: if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x].logP
: if TRUE, probabilities p are given as ln(p).
Usage:
const libR = require('lib-r-math.js');
const { Poisson } = libR;
const seq = libR.R.seq()();
const precision = libR.R.numberPrecision(9);
const { dpois, ppois, qpois, rpois } = Poisson();
const x = seq(0, 10, 2);
const p1 = ppois(x, 1, false, true);
precision(p1);
const p2 = ppois(x, 4);
precision(p2);
const p3 = ppois(x, 10);
precision(p3);
Equivalent in R
options(scipen=999)
options(digits=9)
x = seq(0,10,2);
> ppois(x, 1, FALSE, TRUE);
[1] -0.458675145 -2.521968260 -5.610333983 -9.393768750 -13.697547451
[6] -18.415915478
> ppois(x, 4);
[1] 0.0183156389 0.2381033056 0.6288369352 0.8893260216 0.9786365655
[6] 0.9971602339
> ppois(x, 10);
[1] 0.0000453999298 0.0027693957155 0.0292526880770 0.1301414208825
[5] 0.3328196787507 0.5830397501930
qpois
The quantile function of the Poisson distribution. See R doc.
typescript decl
declare function qpois(
p: number | number[],
lambda: number,
lowerTail: boolean = true,
logP: boolean = false
): number | number[];
p
: probabilities, scalar or array.lambda
: the lambda λ
parameter from the Poisson distribution.lowerTail
: if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x].logP
: if TRUE, probabilities p are given as ln(p).
Usage:
const libR = require('lib-r-math.js');
const { Poisson, R: { arrayrify } } = libR;
const seq = libR.R.seq()();
const log = arrayrify(Math.log);
const precision = libR.R.numberPrecision(9);
const { dpois, ppois, qpois, rpois } = Poisson();
const p = seq(0, 1, 0.2);
const q1 = qpois(ln(p), 1, false, true);
precision(q1);
const q2 = qpois(p, 4);
precision(q2);
const q3 = qpois(p, 10);
precision(q3);
Equivalent in R
options(scipen=999)
options(digits=9)
p = seq(0,10,2);
> qpois( ln(p) , 1, FALSE, TRUE)
[1] Inf 2 1 1 0 0
> qpois(p, 4);
[1] 0 2 3 4 6 Inf
> qpois(p, 10);
[1] 0 7 9 11 13 Inf
rpois
Generate random deviates for the Poisson distribution. See R doc.
typescript decl
declare function rpois(N: number, lambda: number): number | number[];
Usage:
const libR = require('lib-r-math.js');
const {
Poisson,
rng: { MersenneTwister },
rng: { normal: { Inversion } }
} = libR;
const precision = libR.R.numberPrecision(9);
const mt = new MersenneTwister(0);
const { dpois, ppois, qpois, rpois } = Poisson(new Inversion(mt));
mt.init(123);
const r1 = rpois(5, 1);
precision(r1);
const r2 = rpois(5, 4);
precision(r2);
const r3 = rpois(5, 10);
precision(r3);
Equivalent in R
options(scipen=999)
options(digits=9)
RNGkind("Mersenne-Twister", normal.kind="Inversion")
set.seed(123);
> rpois(5, 1);
[1] 0 2 1 2 3
> rpois(5, 4);
[1] 1 4 7 4 4
> rpois(5, 10);
[1] 15 11 5 4 13
Wilcoxon signed rank statistic distribution
dsignrank, psignrank, qsignrank, rsignrank
Density, distribution function, quantile function and random generation for the distribution of the Wilcoxon Signed Rank statistic. See R doc.
Usage:
const libR = require('lib-r-math.js');
const { SignRank, rng: { MarsagliaMultiCarry } } = libR;
const precision = libR.R.numberPrecision(9);
const defaultSR = SignRank();
const mmc = new MarsagliaMultiCarry(4535);
const explicitSR = SignRank(mmc);
const { dsignrank, psignrank, qsignrank, rsignrank } = explicitSR;
dsignrank
The probability mass function of the Wilcoxon Signed Rank statistic. See R doc.
typescript decl
declare function dsignrank(
x: number | number[],
n: number,
aslog: boolean = false
): number | number[];
x
: quantiles (scalar or array of values the rank W+).n
: total number of observations.asLog
: give probabilities as ln(p). Default is false.
Usage:
const libR = require('lib-r-math.js');
const { SignRank } = libR;
const precision = libR.R.numberPrecision(9);
const { dsignrank, psignrank, qsignrank, rsignrank } = SignRank();
const d1 = dsignrank(seq(0, 5), 9);
precision(d1);
const d2 = dsignrank(seq(3, 8), 4);
precision(d2);
const d3 = dsignrank(seq(15, 20), 11);
precision(d3);
Equivalent in R
> dsignrank(seq(0,5), 9);
[1] 0.001953125 0.001953125 0.001953125 0.003906250 0.003906250 0.005859375
> dsignrank(seq(3,8), 4);
[1] 0.1250 0.1250 0.1250 0.1250 0.1250 0.0625
> dsignrank( seq(15,20) , 11);
[1] 0.01074219 0.01220703 0.01367187 0.01562500 0.01708984 0.01904297
psignrank
The cumulative probability function of the Wilcoxon Signed Rank statistic. See R doc.
typescript decl
declare function psignrank(
q: number | number[],
n: number,
lowerTail: boolean = true,
logP: boolean = false
): number | number[];
q
: quantiles (scalar or array of values the rank W+).n
: total number of observations.lowerTail
: if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x].logP
: if TRUE, probabilities p are given as ln(p).
Usage:
const libR = require('lib-r-math.js');
const { SignRank } = libR;
const precision = libR.R.numberPrecision(9);
const { dsignrank, psignrank, qsignrank, rsignrank } = SignRank();
const p1 = psignrank(seq(0, 5), 9);
precision(p1);
const p2 = psignrank(seq(3, 8), 4);
precision(p2);
const p3 = psignrank(seq(15, 20), 11);
precision(p3);
Equivalent in R
options(scipen=999)
options(digits=9)
psignrank(seq(0,5), 9);
psignrank(seq(3,8), 4)
psignrank(seq(15, 20), 11);
qsignrank
The quantile function of the Wilcoxon Signed Rank statistic. See R doc.
typescript decl
declare function qsignrank(
p: number | number[],
n: number,
lowerTail: boolean = true,
logP: boolean = false
): number | number[];
p
: probabilities.n
: total number of observations.lowerTail
: if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x].logP
: if TRUE, probabilities p are given as ln(p).
Usage:
const libR = require('lib-r-math.js');
const { SignRank } = libR;
const { dsignrank, psignrank, qsignrank, rsignrank } = SignRank();
qsignrank(seq(0, 1, 0.2), 9);
qsignrank(seq(0, 1, 0.2), 4);
qsignrank(log(seq(0, 1, 0.2)), 11, false, true);
Equivalent in R
> qsignrank(seq(0, 1, 0.2), 9)
[1] 0 15 20 25 30 45
> qsignrank(seq(0, 1, 0.2), 4);
[1] 0 3 4 6 7 10
> qsignrank(log(seq(0, 1, 0.2)), 11, FALSE, TRUE);
[1] NaN 43 36 30 23 0
rsignrank
Generates random deviates for the Wilcoxon Signed Rank statistic. See R doc.
typescript decl
declare function rsignrank(N: number, n: number): number | number[];
N
: Number of deviates to generate..n
: total number of observations.
Usage:
const libR = require('lib-r-math.js');
const { SignRank } = libR;
const mmc = new MarsagliaMultiCarry(0);
const explicitSR = SignRank(mmc);
const { dsignrank, psignrank, qsignrank, rsignrank } = explicitSR;
mmc.init(4569);
rsignrank(5, 9);
rsignrank(5, 25);
rsignrank(5, 4);
Equivalent in R
RNGkind('Marsaglia-Multicarry');
set.seed(4569)
> rsignrank(5, 9);
[1] 17 15 32 12 20
> rsignrank(5, 25);
[1] 140 80 125 198 157
> rsignrank(5, 4)
[1] 4 7 8 10 8
Student T distribution
dt, pt, qt, rt
Density, distribution function, quantile function and random generation for the distribution of the Student T distribution. See R doc.
Usage:
const libR = require('lib-r-math.js');
const {
StudentT,
rng: { MarsagliaMultiCarry },
rng: { normal: { AhrensDieter } }
} = libR;
const defaultT = StudentT();
const mmc = new MarsagliaMultiCarry(0);
const ad = new AhrensDieter(mmc);
const explicitT = StudentT(ad);
const { dt, pt, qt, rt } = explicitT;
dt
The density function of the of the Student T distribution. See R doc.
typescript decl
declare function dt(
x: number | number[],
df: number,
ncp?: number,
asLog = false
): number | number[];
x
: quantiles.(Scalar or array).df
: degrees of freedom.ncp
: non-central parameter.asLog
: return result as ln(p);
Usage:
const libR = require('lib-r-math.js');
const { StudentT } = libR;
const seq = libR.R.seq()();
const precision = libR.R.numberPrecision(9);
const { dt, pt, qt, rt } = StudentT();
const x = seq(-2, 2, 0.5);
const d1 = dt(x, 4);
precision(d1);
const d2 = dt(x, 6, 3, true);
precision(d2);
const d3 = dt(x, 40, 0, true);
precision(d3);
Equivalent in R
options(scipen=999)
options(digits=9)
x=seq(-2, 2, 0.5);
dt(x, 4);
dt(x, 6, 3, TRUE);
dt(x, 40, 0, TRUE);
pt
The cumulative probability function of the of the Student T distribution. See R doc.
cdecl
declare function pt(
q: number | number[],
df: number,
ncp?: number,
lowerTail: boolean = true,
logP = false
): number | number[];
q
: quantiles, array or scalar.df
: degrees of freedom.ncp
: non central parameter.lowerTail
: if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x].logP
: if TRUE, probabilities p are given as ln(p).
Usage:
const libR = require('lib-r-math.js');
const { StudentT } = libR;
const seq = libR.R.seq()();
const precision = libR.R.numberPrecision(9);
const { dt, pt, qt, rt } = StudentT();
const x = seq(-2, 2, 0.5);
const p1 = pt(x, 4);
precision(p1);
const p2 = pt(x, 6, 3);
precision(p2);
const p3 = pt(x, 40, 0, true, true);
precision(p3);
Equivalent in R
options(scipen=999)
options(digits=9)
x=seq(-2, 2, 0.5);
pt(x, 4);
pt(x, 6, 3, TRUE);
pt(x, 40, 0, TRUE, TRUE)
qt
The quantile function of the of the Student T distribution. See R doc.
typescript decl
declare function qt(
p: number | number[],
df: number,
ncp?: number,
lowerTail: boolean = true,
logP: boolean = false
): number | number[];
p
: probabilities, array or scalar.df
: degrees of freedom.ncp
: non central parameter.lowerTail
: if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x].logP
: if TRUE, probabilities p are given as ln(p).
Usage:
const libR = require('lib-r-math.js');
const { StudentT } = libR;
const seq = libR.R.seq()();
const precision = libR.R.numberPrecision(9);
const { dt, pt, qt, rt } = StudentT();
const x = seq(-2, 2, 0.5);
const pp1 = pt(x, 4);
const q1 = qt(pp1, 4);
precision(q1);
const pp2 = pt(x, 6, 3);
const q2 = qt(pp2, 6, 3);
precision(q2);
const pp3 = pt(x, 40, 0, true, true);
const q3 = qt(pp3, 40, 0, true, true);
precision(q3);
Equivalent in R
options(scipen=999)
options(digits=9)
x=seq(-2, 2, 0.5);
pp1= pt(x, 4);
qt(pp1, 4)
pp2=pt(x,6,3)
qt(pp2, 6, 3)
pp3 = pt(x, 40, 0, TRUE, TRUE)
qt(pp3, 40, 0, TRUE, TRUE)
rt
Generates deviates for the Student T distribution. See R doc.
typescript decl
declare function rt(n: number, df: number, ncp?: number): number | number[];
n
: number of random deviates to generate.df
: degrees of freedom.ncp
: non central parameter.
Usage:
const libR = require('lib-r-math.js');
const {
StudentT,
rng: { MarsagliaMultiCarry },
rng: { normal: { AhrensDieter } }
} = libR;
const precision = libR.R.numberPrecision(9);
const mmc = new MarsagliaMultiCarry(0);
const ad = new AhrensDieter(mmc);
const { dt, pt, qt, rt } = StudentT(ad);
mmc.init(1234);
const r1 = rt(5, 4);
precision(r1);
mmc.init(4345);
const r2 = rt(5, 11, 3);
precision(r2);
mmc.init(9876);
const r3 = rt(5, 26, -16);
precision(r3);
Equivalent in R
RNGkind("Marsaglia-Multicarry",normal.kind="Ahrens-Dieter")
options(scipen=999)
options(digits=9)
set.seed(1234);
rt(5, 4);
set.seed(4345);
rt(5, 11, 3);
set.seed(9876)
rt(5, 26, -16);
Studentized Range distribution, (Tukey HSD)
ptukey, qtukey
The Tukey studentized range (1 - α confidence interval) for post hoc analysis when (for example 1 way anova
).
Compare individual means to find rejection of $u_{j} \neq u_{i}$. See R doc and wiki.
For 1 way anova
having k
groups containing $n_{i}$ samples and $T_{i}$ group means:
Then the (1 - α) confidence interval for each $u_{j} \neq u_{i}$ comparison will be:
$$ \left(T_{i} - T_{j} \right) - q_{\alpha,k,v} \cdot \sqrt{ S^2/k } \lt u_{i} - u_{j} \lt \left(T_{i} - T_{j} \right) + q_{\alpha,k,v} \cdot \sqrt{ S^2/k } $$
With q(α,k,v)
equal to:
qtukey(1-α, k, N-k);
ptukey
The probability function of the Tukey Studentized Range aka Tukey HSD. Usefull it to find the p-value of the difference of 2 specific treatment means $T_{i}-T_{j}$. See R-doc.
typescript decl
declare function ptukey(
q: number|number[],
nmeans: number,
df: number,
nranges: number = 1,
lowerTail: boolean = true,
logP: boolean = false
): number|number[]
q
: number of random deviates to generate.nmeans
: sample size for range (same for each group).df
: degrees of freedom of S².nranges
: number of groups whose maximum range is considered.lowerTail
: if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x].logP
: if TRUE, probabilities p are given as log(p).
Usage:
const libR = require('lib-r-math.js');
const { Tukey } = libR;
const { abs } = Math;
const { qtukey, ptukey } = Tukey();
const differenceOf2Means = -67.46;
const std = 16.69658048823;
const df = 20;
const k = 5;
const pValue = 1 - ptukey(abs(differenceOf2Means) / std, k, df)
R equivalent
p_value = 1 - ptukey(abs(-67.46)/16.69658048823, 5, 20)
qtukey
The quantile function of the Tukey Studentized Range. See R-doc.
typescript decl
declare function qtukey(
p: number|number[],
nmeans: number,
df: number,
nranges: number = 1,
lowerTail: boolean = true,
logP: boolean = false
): number|number[]
q
: probabilities.nmeans
: sample size for range (same for each group).df
: degrees of freedom of S².nranges
: number of groups whose maximum range is considered.lowerTail
: if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x].logP
: if TRUE, probabilities p are given as log(p).
Usage:
const libR = require('lib-r-math.js');
const {
Tukey,
R: { seq:_seq, numberPrecision }
} = libR;
const prec3 = numberPrecision(3);
const seq = _seq()();
const { ptukey, qtukey } = Tukey();
const row1 = seq(2,10).map(v => qtukey(0.95,v, 5));
prec3(row1);
prec3(seq(2,10).map(v => qtukey(0.95,v, 6)))
prec3(seq(2,10).map(v => qtukey(0.95,v, 7)));
prec3(seq(2,10).map(v => qtukey(0.95,v, 8)));
Equivalent in R
options(digits=3)
qtukey(p=0.95, nmeans=2:10, df= 5)
qtukey(p=0.95, nmeans=2:10, df= 6)
qtukey(p=0.95, nmeans=2:10, df= 7)
qtukey(p=0.95, nmeans=2:10, df= 8)
Tukey HSD for 1-α = 0.95 | k = Number of treatments |
---|
|
df for Error Term | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
---|
5 | 3.64 | 4.60 | 5.22 | 5.67 | 6.03 | 6.33 | 6.58 | 6.80 | 6.99 |
6 | 3.46 | 4.34 | 4.9 | 5.3 | 5.63 | 5.9 | 6.12 | 6.32 | 6.49 |
7 | 3.34 | 4.16 | 4.68 | 5.06 | 5.36 | 5.61 | 5.82 | 6 | 6.16 |
8 | 3.26 | 4.04 | 4.53 | 4.89 | 5.17 | 5.4 | 5.6 | 5.77 | 5.92 |
Weibull distribution
dweibull, pweibull, qweibull, rweibull
Density, distribution function, quantile function and random generation for the Weibull distribution. See R doc.
Usage:
const libR = require('lib-r-math.js');
const {
Weibull,
rng: { WichmannHill }
} = libR;
const wh = new WichmannHill(1234);
const explicitW = Weibull(wh);
const defaultW = Weibull();
const { dweibull, pweibull, qweibull, rweibull } = explicitW;
dweibull
The density function of the Weibull distribution with parameters shape
(λ) and scale
(k). See R doc.
typescript decl
declare function dweibull(
x: number|number[],
shape: number,
scale: number = 1,
aslog: boolean = false
): number|number[];
x
: quantiles (scalar or Array)shape
: shape parameterscale
: scale parameterasLog
: return result p as ln(p).
Usage:
const libR = require('lib-r-math.js');
const {
Weibull,
R: { seq: _seq, numberPrecision }
} = libR;
const seq = _seq()();
const precision = numberPrecision(9);
const { dweibull, pweibull, qweibull, rweibull } = Weibull();
const x = seq(0, 10, 2);
const x2 = [...seq(0, 1, 0.2), Infinity];
const d1 = dweibull(x, 1, 2);
precision(d1);
const d2 = dweibull(x, 0.5, 2);
precision(d2);
const d3 = dweibull(x2, 1.5, 9);
precision(d3);
Equivalent in R
options(scipen=999)
options(digits=9)
x = seq(0, 10, 2);
x2 = c(seq(0, 1, 0.2), Inf);
dweibull(x, 1, 2)
dweibull(x, 0.5, 2)
dweibull(x2, 1.5, 9);
pweibull
The cummulative probability function of the Weibull distribution with parameters shape
(λ) and scale
(k). See R doc.
typescript decl
declare function pweibull(
q: number,
shape: number,
scale: number = 1,
lowerTail: boolean = true,
logP: boolean = false
): number|number[];
q
: quantiles (scalar or Array)shape
: shape parameterscale
: scale parameterlowerTail
: if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x].logP
: if true
, probabilities p are given as ln(p).
Usage:
const libR = require('lib-r-math.js');
const {
Weibull,
R: { seq:_seq, numberPrecision }
} = libR;
const seq = _seq()();
const precision = numberPrecision(9);
const { dweibull, pweibull, qweibull, rweibull } = Weibull();
const x = seq(0, 10, 2);
const x2 = [...seq(0, 1, 0.2), Infinity];
const p1 = pweibull(x, 1, 2);
precision(p1);
const p2 = pweibull(x, 0.5, 2);
precision(p2);
const p3 = pweibull(x2, 1.5, 9);
precision(p3);
Equivalent in R
options(scipen=999)
options(digits=9)
x = seq(0, 10, 2);
x2 = c(seq(0, 1, 0.2), Inf);
pweibull(x, 1, 2)
pweibull(x, 0.5, 2)
pweibull(x2, 1.5, 9)
qweibull
The quantile function of the Weibull distribution with parameters shape
(λ) and scale
(k). See R doc.
typescript decl
declare function qweibull(
p: number|number[],
shape: number,
scale: number = 1,
lowerTail: boolean = true,
logP: boolean = false
): number|number[];
p
: probabilities (scalar or Array)shape
: shape parameterscale
: scale parameterlowerTail
: if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x].logP
: if true
, probabilities p are given as ln(p).
Usage:
const libR = require('lib-r-math.js');
const {
Weibull,
R: { seq:_seq, numberPrecision }
} = libR;
const seq = _seq()();
const precision = numberPrecision(9);
const { dweibull, pweibull, qweibull, rweibull } = Weibull();
const pp = seq(0, 1, 0.2);
const q1 = qweibull(pp, 1, 2);
precision(q1);
const q2 = qweibull(pp, 0.5, 2);
precision(q2);
const q3 = qweibull(pp, 1.5, 9);
precision(q3)
Equivalent in R
options(scipen=999)
options(digits=9)
pp = seq(0, 1, 0.2);
qweibull(pp, 1, 2);
qweibull(pp, 0.5, 2);
qweibull(pp, 1.5, 9);
rweibull
Generates random deviates for the Weibull distribution with parameters shape
(λ) and scale
(k). See R doc.
typescript decl
declare function rweibull(
N: number,
shape: number,
scale: number = 1
): number | number[];
n
: Number of deviates to generate.shape
: shape parameterscale
: scale parameter
Usage:
const libR = require('lib-r-math.js');
const {
Weibull,
rng: { WichmannHill },
R: { numberPrecision }
} = libR;
const precision = numberPrecision(9);
const wh = new WichmannHill(1234);
const { dweibull, pweibull, qweibull, rweibull } = Weibull(wh);
const r1 = rweibull(5, 1, 2);
precision(r1);
const r2 = rweibull(5, 0.5, 2);
precision(r2);
const r3 = rweibull(5, 1.5, 9);
precision(r3);
Equivalent in R
RNGkind("Wichmann-Hill");
set.seed(1234)
rweibull(5, 1, 2);
rweibull(5, 0.5, 2);
rweibull(5, 1.5, 9);
Wilcoxon rank sum statistic
distribution
dwilcox, pwilcox, qwilcox, rwilcox
The Wilcoxon rank sum test is also known as the Mann–Whitney U test
Density, distribution function, quantile function and random generation for the Wilcoxon rank sum statistic. See R doc.
These functions are members of an object created by the Wilcoxon
factory method. The factory method needs as optional argument an instance of one of the uniform PRNG generators.
Note: some small improvements where made to dwilcox, pwilcox, qwilcox
when porting from R.
Read about it [here]((#what-is-improved-on-r).
Usage:
const libR = require('lib-r-math.js');
const {
Wilcoxon
rng: { SuperDuper }
} = libR;
const sp = new SuperDuper(1234);
const explicitW = Wilcoxon(sp);
const defaultW = Wilcoxon();
const { dwilcox, pwilxoc, qwilcox, rwilcox } = defaultW;
dwilcox
The density function of the Wilcoxon rank sum statistic. See R doc.
typescript decl
declare function dwilcox(
x: number|number[],
m: number,
n: number,
asLog: boolean = false
): number|number[]
x
: quantile(s), scalar or array of values.m
: size of first sample, the convention is to have m ≤ n.n
: size of the second sample, the convention is n ≥ m.asLog
: return value as ln(p)
Note: if m
≥ n
the values are swapped internally.
Usage:
const libR = require('lib-r-math.js');
const {
Wilcoxon,
R: { seq:_seq , numberPrecision, arrayrify }
} = libR;
const seq = _seq()();
const precision = numberPrecision(9);
const pow = arrayrify(Math.pow);
const { dwilcox, pwilcox, qwilcox, rwilcox } = Wilcoxon();
const x = pow( seq(0,10,2), 2);
const d1 = dwilcox(x, 8, 9);
precision(d1)
const d2 = dwilcox(x, 100, 50);
precision(d2);
const d3 = dwilcox(x, 5, 34);
precision(d3);
Equivalent in R
x = seq(0,10,2)^2;
dwilcox(x, 8, 9);
dwilcox(x, 100, 50);
dwilcox(x, 5, 34);
pwilcox
The cumulative probability function of the Wilcoxon rank sum statistic. See R doc.
typescript decl
declare function pwilcox(
q: number|number[],
m: number,
n: number,
lowerTail: boolean = true,
logP: boolean = false
): number|number[]
q
: quantile(s), scalar or array of values.m
: size of first sample, the convention is to have m ≤ n.n
: size of the second sample, the convention is n ≥ m.lowerTail
: if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x].logP
: if true
, probabilities p are given as ln(p).
Note: if m
≥ n
the values are swapped internally.
Usage:
const libR = require('lib-r-math.js');
const {
Wilcoxon,
R: { seq:_seq , numberPrecision, arrayrify }
} = libR;
const seq = _seq()();
const precision = numberPrecision(9);
const pow = arrayrify(Math.pow);
const { dwilcox, pwilcox, qwilcox, rwilcox } = Wilcoxon();
const q = pow( seq(0,10,2), 2);
const p1 = pwilcox(q, 8, 9);
precision(p1)
const p2 = pwilcox(q, 100, 50);
precision(p2);
const p3 = pwilcox(q, 5, 34);
precision(p3);
Equivalent in R
options(scipen=999)
options(digits=9)
q = seq(0, 10, 2)^2;
pwilcox(q, 8, 9)
pwilcox(q, 100, 50);
pwilcox(q, 5, 34);
qwilcox
The quantily function of the Wilcoxon rank sum statistic. See R doc.
typescript decl
declare function qwilcox(
p: number|number[],
m: number,
n: number,
lowerTail: boolean = true,
logP: boolean = false
): number|number[]
p
: probabilities, scalar or array of values.m
: size of first sample, the convention is to have m ≤ n.n
: size of the second sample, the convention is n ≥ m.lowerTail
: if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x].logP
: if true
, probabilities p are given as ln(p).
Note: if m
≥ n
the values are swapped internally.
Usage:
const libR = require('lib-r-math.js');
const {
Wilcoxon,
R: { seq:_seq }
} = libR;
const seq = _seq()();
const { dwilcox, pwilcox, qwilcox, rwilcox } = Wilcoxon();
const p = seq(0,1,0.2);
const q1 = qwilcox(p, 8, 9);
const q2 = qwilcox(p, 100, 50);
const q3 = qwilcox(p, 5, 34);
Equivalent in R
p = seq(0,1,0.2);
qwilcox(p, 8, 9);
qwilcox(p, 100, 50);
qwilcox(p, 5, 34);
rwilcox
Generates random deviates for of the Wilcoxon rank sum statistic. See R doc.
typescript decl
declare function rwilcox(
nn: number,
m: number,
n: number
): number|number[];
nn
: number of deviates to generate.m
: size of first sample, the convention is to have m ≤ n.n
: size of the second sample, the convention is n ≥ m.
Note: if m
≥ n
the values are swapped internally.
Usage:
const libR = require('lib-r-math.js');
const {
Wilcoxon,
rng: { SuperDuper }
} = libR;
const sd = new SuperDuper(1234);
const { dwilcox, pwilcox, qwilcox, rwilcox } = Wilcoxon(sd);
sd.init(1234);
rwilcox(5, 8, 9);
rwilcox(5, 100, 50);
rwilcox(5, 5, 34)
Equivalent in R
RNGkind("Super-Duper");
set.seed(1234);
rwilcox(5, 8, 9);
rwilcox(5, 100, 50);
rwilcox(5, 5, 34);
--
Special Functions of Mathematics
Special functions are particular mathematical functions which have more or less established names and notations due to their importance in mathematical analysis, functional analysis, physics, or other applications.
There is no general formal definition, but the list of mathematical functions contains functions which are commonly accepted as special.
Bessel functions
besselJ, besselY, besselI, besselK
Bessel Functions of integer and fractional order, of first and second kind, J(nu) and Y(nu), and Modified Bessel functions (of first and third kind), I(nu) and K(nu). See R doc.
Usage:
const libR = require('lib-r-math.js');
const {
special: { besselJ, besselK, besselI, besselY }
} = libR;
besselJ
Bessel function of first kind. See R doc.
typescript decl
declare function besselJ(
x: number|number[],
nu: number|number[]
): number|number[];
x
: input value x ≥ 0.nu
: order, (may be fractional!)
Note: if x
and nu
are arrays or (scalar/array combinations)
of unequal length then R argument cycling rules apply.
Usage:
const libR = require('lib-r-math.js');
const {
special: { besselJ, besselK, besselI, besselY },
R: { map, numberPrecision, c }
} = libR;
const _9 = numberPrecision(9);
let xJ = c(1, 7.389, 20.09, 7.389, 403.4, 1097,
0.3679, 8103, 22030, 0.04979, 7.389, 1097);
let nuJ = c(11.02, 0.1353, 0.4066, 54.6, 63.43, 73.7,
-3.669, -0.4066, -1.221, -63.43, -54.6, -73.7);
const bJ = _9(besselJ(xJ, nuJ));
Equivalent in R
x = c(1, 7.389, 20.09, 7.389, 403.4, 1097, 0.3679, 8103, 22030, 0.04979, 7.389, 1097);
nu = c(11.02, 0.1353, 0.4066, 54.6, 63.43, 73.7, -3.669, -0.4066, -1.221, -63.43, -54.6, -73.7);
besselJ(x,nu);
besselY
Bessel function of the second kind. See R doc.
typescript decl
export function besselY(
x: number|number[],
nu: number|number[]
): number|number[];
x
: input value x ≥ 0.nu
: order, (may be fractional!)
Note: if x
, nu
, or expo
are arrays or (scalar/array combinations)
of unequal length then R argument cycling rules apply.
Usage:
const libR = require('lib-r-math.js');
const {
special: { besselJ, besselK, besselI, besselY },
R: { map, numberPrecision, c }
} = libR;
const _9 = numberPrecision(9);
let xY = c(0.1353, 148.4, 22030, 20.09, 403.4, 1097, 0.1353, 2.718, 2981, 1, 8103, 22030);
let nuY = c(1.221, 3.669, 1.221, 63.43, 63.43,
73.7, -1.221, -33.12, -0.1353, -63.43, -63.43, -73.7);
const bY = _9(besselY(xY, nuY));
Equivalent in R
xY = c(0.1353, 148.4, 22030, 20.09, 403.4, 1097, 0.1353, 2.718, 2981, 1, 8103, 22030);
nuY = c(1.221, 3.669, 1.221, 63.43, 63.43,
73.7, -1.221, -33.12, -0.1353, -63.43, -63.43, -73.7);
besselY(xY, nuY);
besselI
Modified Bessel functions of first kind. See R doc.
typescript decl
declare function besselI(
x: number|number[],
nu: number|number[],
expo: boolean|boolean[] = false
): number;
x
: input value x ≥ 0.nu
: order, (may be fractional!)expo
: if TRUE, the results are scaled in order to avoid overflow exp(-x)*BesselI(x;nu)
.
Note: if x
, nu
, or expo
are arrays or (scalar/array combinations)
of unequal length then R argument cycling rules apply.
Usage:
const libR = require('lib-r-math.js');
const {
special: { besselJ, besselK, besselI, besselY },
R: { map, numberPrecision, c }
} = libR;
const _9 = numberPrecision(9);
let xI = c(0.3679, 1, 22030, 0.04979, 54.6, 403.4,
0.04979, 2981, 8103, 0.1353, 0.3679, 2.718);
let nuI = c(3.669, 11.02, 1.221, 63.43, 73.7, 63.43,
-0.4066, -0.1353, -0.4066, -73.7, -54.6, -73.7);
const bI = _9( besselI(xI, nuI, true) );
Equivalent in R
xI=c(0.3679, 1, 22030, 0.04979, 54.6, 403.4,
0.04979, 2981, 8103, 0.1353, 0.3679, 2.718);
nuI=c(3.669, 11.02, 1.221, 63.43, 73.7, 63.43,
-0.4066, -0.1353, -0.4066, -73.7, -54.6, -73.7);
besselI(xI, nuI, TRUE)
besselK
Modified Bessel functions of third kind. See R doc.
typescript decl
declare function besselK(
x: number|number[],
nu: number|number[],
expo: boolean|boolean[] = false
): number;
x
: input value x ≥ 0.nu
: order, (may be fractional!)expo
: if TRUE, the results are scaled in order to avoid underflow exp(x)*BesselK(x;nu)
.
Note: if x
, nu
, or expo
are arrays or (scalar/array combinations)
of unequal length then R argument cycling rules apply.
Usage:
const libR = require('lib-r-math.js');
const {
special: { besselJ, besselK, besselI, besselY },
R: { map, numberPrecision, flatten:c }
} = libR;
const _9 = numberPrecision(9);
let xK=c(0.3679, 2.718, 403.4, 1, 54.6, 2981, 0.3679, 148.4,
22030, 0.1353, 2.718, 148.4 );
let nuK= c(3.669, 33.12, 11.02, 63.43, 73.7, 54.6, -3.669, -3.669,
-1.221, -73.7, -73.7, -54.6);
const bK = _9( besselK(xK, nuK, true) );
Equivalent in R
options(digits=9)
xK=c(0.3679, 2.718, 403.4, 1, 54.6, 2981, 0.3679, 148.4,
22030, 0.1353, 2.718, 148.4 );
nuK= c(3.669, 33.12, 11.02, 63.43, 73.7, 54.6, -3.669, -3.669, -1.221, -73.7, -73.7, -54.6);
besselK(xK, nuK, TRUE);
Beta functions
beta, lbeta
The functions beta
and lbeta
return the beta function and the natural logarithm of the beta function.
See R doc.
beta
The beta function defined for postive x
and y
by:
$$ \mathrm {B}(x,y) = \frac{ \Gamma(x) \cdot \Gamma(y)}{\Gamma(x+y)} $$
typescript decl
declare function beta(
a: number | number[],
b: number | number[]
): number | number[];
a
: non-negative (scalar or array). See wikib
: non-negative (scalar or array). See wiki
Usage:
const libR = require('lib-r-math.js');
const {
special: { beta, lbeta },
R: { flatten: c }
} = libR;
const b1 = beta(4, 5);
const b2 = beta(c(0.5, 100), c(0.25, 50));
Equivalence in R
beta(4, 5);
beta(c(0.5, 100), c(0.25, 50));
lbeta
The natural logarithm of the beta function.
typescript decl
declare function lbeta(
a: number | number[],
b: number | number[]
): number | number[];
a
: non-negative (scalar or array). See wikib
: non-negative (scalar or array). See wiki
Usage:
const libR = require('lib-r-math.js');
const {
special: { beta, lbeta },
R: { flatten: c }
} = libR;
const lb1 = lbeta(4, 5);
const lb2 = lbeta(c(0.5, 100), c(0.25, 50));
Equivalence in R
lbeta(4, 5);
lbeta(c(0.5, 100), c(0.25, 50))
Gamma functions
digamma, trigamma, pentagamma, tetragamma, psigamma
, gammma
, lgamma
.
The functions gammaand lgamma return the gamma function Γ(x) and the natural logarithm of the absolute value of the gamma function: ln|[Γ(x)|
.
The functions digamma
, trigamma
, pentagamma
, tetragamma
and psigamma
return repectivily the first, second, third and fourth derivatives and n-th derivatives
of the logarithm of the gamma function ln{ Γ(x) }. See R doc.
digamma
The first derivative ψ(x) of the natural logarithm of the gamma function
Alias for psigmma function with the deriv
argument set to 0
.
Aka psigamma(x, 0)
.
$$ ψ(x) = \frac{d}{dx} (ln Γ(x) )= \frac{Γ'(x)}{ Γ(x)} $$
typescript decl
declare function digamma(
x: number|number[]
): number|number[];
Usage:
const libR = require('lib-r-math.js');
const {
special: { digamma },
R: { numberPrecision, seq: _seq, flatten: c }
} = libR;
const seq = _seq()();
const pow = multiplex(Math.pow);
const precision9 = numberPrecision(9);
const x = c(0, pow(4, seq(1, 10, 2)), Infinity);
const dig1 = precision9(digamma(x));
Equivalent in R
x = c(0, 4^seq(1, 10, 2), Inf);
digamma(x);
trigamma
The 2nd derivative of ln Γ(x)
. See R doc
$$ ψ(x)' = \frac{d²}{dx²} (ln Γ(x) )$$
typescript decl
declare function trigamma(
x:number|number[]
):number|number[];
Usage:
const libR = require('lib-r-math.js');
const {
special: { trigamma },
R: { numberPrecision, seq: _seq, flatten: c }
} = libR;
const seq = _seq()();
const pow = multiplex(Math.pow);
const precision9 = numberPrecision(9);
const x = c(0, pow(4, seq(1, 10, 2)), Infinity);
const tri1 = precision9(trigamma(x));
Equivalent in R
x = c(0, 4^seq(1, 10, 2), Inf );
trigamma(x);
tetragamma
The 3rd derivative of ln Γ(x)
. This function is deprecated in R
.
tetragamma(x)
is an alias for psigamma(x,2)
.
$$ ψ(x)³ = \frac{d²}{dx²} (ln Γ(x) )$$
typescript decl
declare function tetragamma(
x:number|number[]
):number|number[];
Usage:
const libR = require('lib-r-math.js');
const {
special: { tetragamma },
R: { numberPrecision, seq: _seq, flatten: c }
} = libR;
const seq = _seq()();
const pow = multiplex(Math.pow);
const precision9 = numberPrecision(9);
const x = c(0, pow(4, seq(1, 10, 2)), Infinity);
const tetra1 = precision9(tetragamma(x));
Equivalent in R
x = c(0, 4^seq(1, 10, 2), Inf );
psigamma(x,2);
pentagamma
The 4th derivative of ln Γ(x)
. This function is deprecated in R
.
pentagamma(x)
is an alias for psigamma(x,3)
.
$$ ψ³(x) = \frac{d⁴}{dx⁴} (ln Γ(x) )$$
typescript decl
declare function pentagamma(
x:number|number[]
):number|number[];
Usage:
const libR = require('lib-r-math.js');
const {
special: { pentagamma },
R: { numberPrecision, seq: _seq, flatten: c }
} = libR;
const seq = _seq()();
const pow = multiplex(Math.pow);
const precision9 = numberPrecision(9);
const x = c(0, pow(4, seq(1, 10, 2)), Infinity);
const penta1 = precision9(pentagamma(x));
Equivalent in R
x = c(0, 4^seq(1, 10, 2), Inf );
psigamma(x,3);
[1] Inf 4.486533e-02 7.810071e-06 1.865375e-09 4.547890e-13
[6] 1.110229e-16 0.000000e+00
psigamma
The nth derivative of ln Γ(x)
.
$$ ψ(x)^{n} = \frac{d^{n}}{dx^{n}} (ln Γ(x) )$$
typescript decl
declare function psigamma(
x:number|number[],
deriv: number|number[]
):number|number[];
Usage:
const libR = require('lib-r-math.js');
const {
special: { psigamma },
R: { numberPrecision, seq: _seq, flatten: c }
} = libR;
const seq = _seq()();
const pow = multiplex(Math.pow);
const precision9 = numberPrecision(9);
const psi1 = precision9(psigamma(x, 9));
Equivalent in R
x = c(0, 4^seq(1, 10, 2), Inf );
psigamma(x, 9)
gammma
The gammma function Γ(x). See R doc.
typescript decl
declare function gamma(
x: number|number[]
): number|number[]
Usage:
const libR = require('lib-r-math.js');
const {
special: { gamma },
R: { numberPrecision, seq: _seq, flatten: c }
} = libR;
const seq = _seq()();
const precision9 = numberPrecision(9);
const gx = seq(2,5,.5).map(x=> x*x-9);
const g = precision9(gamma(gx));
Equivalent in R
gx => seq(2, 5, .5)^2 - 9.125;
gamma(gx);
lgammma
The logarithmic gammma function Γ(x). See R doc.
typescript decl
declare function lgamma(
x: number|number[]
): number|number[]
Usage:
const libR = require('lib-r-math.js');
const {
special: { lgamma },
R: { numberPrecision, seq: _seq, flatten: c }
} = libR;
const seq = _seq()();
const precision9 = numberPrecision(9);
const gx = seq(2,5,.5).map(x=> x*x-9);
const g = precision9(lgamma(gx));
Equivalent in R
gx = seq(2,5,.5)^2-9;
lgamma(gx);
Binomial coefficient functions
choose, lchoose
The functions choose
and lchoose
return binomial coefficients and the logarithms of their absolute values.See R doc.
choose
Returns the binomial coefficient of n over k
${n}\choose{k}$.
typescript decl
declare function choose(
n: number|number[],
k: number|number[]
): number|number[]
n
: scalar or array of numbersk
: scalar or array of numbers
Note: if n
and k
are unequal sized arrays then R argument cycling rules apply.
Usage:
const libR = require('lib-r-math.js');
const {
special: { choose },
R: { seq: _seq, flatten: c }
} = libR;
const coef1 = choose(4, c(0, 1, 2, 3, 4));
const coef2 = choose(4000, 30);
const coef3 = choose(2000, 998);
Equivalent in R
choose(4, c(0,1,2,3,4) );
choose(4000,30);
choose(2000,998);
lchoose
Returns the natural logarithm binomial coefficient of n over k
${n}\choose{k}$.
typescript decl
declare function choose(
n: number|number[],
k: number|number[]
): number|number[]
n
: scalar or array of numbersk
: scalar or array of numbers
Note: if n
and k
are unequal sized arrays then R argument cycling rules apply.
Usage:
const libR = require('lib-r-math.js');
const {
special: { choose },
R: { seq: _seq, flatten: c }
} = libR;
const lcoef1 = lchoose(4, c(0, 1, 2, 3, 4));
const lcoef2 = lchoose(4000, 30);
const lcoef3 = lchoose(2000, 998);
Equivalent in R
lchoose(4, c(0,1,2,3,4) );
lchoose(4000,30);
lchoose(2000,998);
Contributor Covenant Code of Conduct
Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
Our Standards
Examples of behavior that contributes to creating a positive environment include:
Using welcoming and inclusive language
Being respectful of differing viewpoints and experiences
Gracefully accepting constructive criticism
Focusing on what is best for the community
Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
The use of sexualized language or imagery and unwelcome sexual attention or advances
Trolling, insulting/derogatory comments, and personal or political attacks
Public or private harassment
Publishing others' private information, such as a physical or electronic address, without explicit permission
Other conduct which could reasonably be considered inappropriate in a professional setting
Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting Ben Lesh (ben@benlesh.com), Tracy Lee (tracy@thisdot.co) or OJ Kwon (kwon.ohjoong@gmail.com). All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
Attribution
This Code of Conduct is adapted from the Contributor Covenant, version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
Changelog
All notable changes to this project will be documented in this file.
The format is based on Keep a Changelog,
and this project adheres to Semantic Versioning.
[Unreleased]
Changed
Changed
Removed
Guiding Principles
Changelogs are for humans, not machines.
There should be an entry for every single version.
The same types of changes should be grouped.
Versions and sections should be linkable.
The latest version comes first.
The release date of each version is displayed.
Mention whether you follow Semantic Versioning.
Types of changes
Added for new features.
Changed for changes in existing functionality.
Deprecated for soon-to-be removed features.
Removed for now removed features.
Fixed for any bug fixes.
Security in case of vulnerabilities.