Gnomon — Standard Library

(back to main)

Contents

General Information

Mathematical Constants

Basic Maths and Trigonometry

Special Functions

Conversion Functions

Arithmetic

Array Functions

Combinatorics

Date Functions

Random Number Generators

Descriptive Statistics

Continuous Distributions

Discrete Distributions

Statistical Tests

Signal Analysis

Polynomial

File I/O

Vectors and Matrices

Numerical Methods

Graphics

Plot Constants

General Information

All built-in functions and constants start with a capital and cannot be re-defined. In the tables below, a (*) indicates functions that support arbitrary precision integer output, and arguments are indicated as follows:

ArgumentDescription ArgumentDescription
z, wcomplex x, y, sreal
pprobability (real in [0,1]) i, j, k, ninteger
b, cbyte ffile identifier
$string [ ]array or matrix
ddictionary *any type
|or @function

(back to top)

Mathematical Constants

FunctionArgumentsDescription
PiPi constant
EE constant
ISquare root of -1
TBoolean true = $1
FBoolean false = $0
PhiThe Golden Ratio
Sqrt2Square root of 2

Basic Maths and Trigonometry

FunctionArgumentsDescription
LnzNatural logarithm (*)
LogzLogarithm to base 10 (*)
ExpzExponential
SqrtzSquare root
InvPowz wReturns the principal value of z^(1/w)
FactnFactorial (*)
BiCon kBinomial coefficient (*)
SinzSine
CoszCosine
TanzTangent
AsinzArcsine
AcoszArccosine
AtanzArctangent
SinhzHyperbolic sine
CoshzHyperbolic cosine
TanhzHyperbolic tangent
AsinhzInverse hyperbolic sine
AcoshzInverse hyperbolic cosine
AtanhzInverse hyperbolic tangent
FloorzFloor
CeilzCeiling
AbszAbsolute value (modulus for complex argument) (*)
SignzReturns +1, 0 or -1 for positive, zero or negative real input, and z/|z| for non-zero complex input (*)

(back to top)

Special Functions

FunctionArgumentsDescription
GammazGamma function
LnGammazLog of the Gamma function
GammaPx yIncomplete Gamma function
GammaQx yComplemented incomplete Gamma function
BetazBeta function
LnBetazLog of the Beta function
BetaIxIncomplete Beta function
BesselJn xBessel function of the first kind, order n
BesselYn xBessel function of the second kind, order n
ErfxError function
ErfcxComplement of the error function
ExpIntxExponential Integral
ZetazRiemann Zeta function
ZetaGenx nGeneralised (2 argument) Real Zeta function

(back to top)

Conversion Functions

FunctionArgumentsDescription
Basen kReturn a string representation of n in base k (from 2 to 16)
Intx|$Convert to integer (truncates)
Decx|$Convert to decimal
FracxConvert to rational (best approximation with configured max denominator)
ComplexxConvert to complex
Str*Convert to string
ToDegxConvert x from radians to degrees
ToRadxConvert x from degrees to radians
Splitx|$Return an array of digits for an integer, the numerator and denominator for a fraction, or characters for a string
Combine[n|$]Combine the given array of digits into a number or characters into a string
NaN*Return true ($1) if NaN

(back to top)

Arithmetic

FunctionArgumentsDescription
ArgzArgument of a complex number
ConjzComplex conjugate
RezReal part of a complex number
ImzImaginary part of a complex number
Chopz nTruncate small deviations from integer values (tolerance 10^-n)
AGMz wReturn the arithmetic geometric mean of the two arguments
GCDz wReturn the greatest common divisor of two arguments (integer or gaussian integer) (*)
LCMz wReturn the least common multiple of two arguments (integer or gaussian integer) (*)
FactorszReturn (probable) prime factors of the argument (over gaussian integers if input is complex) (*)
DivisorszReturn all divisors of the argument
CFxCalculate a continued fraction representation of x to machine precision
FromCF[d]Evaluate the given continued fraction representation

(back to top)

Array Functions

FunctionArgumentsDescription
Sort[z|$]Sort array argument (in place)
KeySort[*] [y]Sort the first array (in place) using the second array y as the key
Rev[*]|$Reverse array or string argument (in place)
Unique[x]Return the unique elements of [x]
Freq[x] [y]Return the number of occurrences in [x] of each element of [y]
ArrayCmp[*] *|[*]When the second argument is an array, return true if the two arrays are element by element equal, else return true if every element of the array is equal to the second argument
Diffs[z]Return an array of the differences between adjacent elements of [z]
Fill[*] z|[z]Fill the given array with the value z or cycle through entries [z]
FillIf[*] [b] z|[z]Fill the entries of the given array selected by the boolean array [b] with the value z or cycle through entries [z]
FnFill[*] @fFill the given array by repeated calls to the function f (handy for random arrays). The function must take either no arguments, or a single integer argument in which case the current index is passed in.
Extracti [[*]]Return the ith column of an array of arrays (useful especially for file data)
Assign[[*]]Auto assign each column of the array to the variable name given by the header (i.e. the values in the first row)
Apply@f [x]Returns vector [ f(x[1]) f(x[2]) ... f(x[n]) ]
Apply2D@f [x] [y]Returns matrix [ [ f(x[1],y[1]) f(x[2],y[1]) ... f(x[n],y[1]) ] [ f(x[1],y[2]) ... ] [ ... f(x[n],y[m]) ] ]

(back to top)

Combinatorics

FunctionArgumentsDescription
Shuffle[*]Shuffle the array argument (in place)
Sample[*] n bTake n samples from a, with replacement if b nonzero
NextPerm[i] nGiven a k-permutation of [1:n] (i.e. a k element order important subset of [1:n]) return the next k-permutation, or NaN if last. Results are undefined if the input array has duplicates.
NextComb[i] nGiven a k-combination of [1:n] (i.e. a k element order unimportant subset of [1:n]) return the next k-combination, or NaN if last. Results are undefined if the input array is unsorted or has duplicates.
NextSubset[i] nGiven a subset of [1:n] return the next subset, or NaN if last. Results are undefined if the input array is unsorted or has duplicates.
NextPart[[i]]Given a partition of [1:n] return the next partition, or NaN if last. Results are undefined if the input parition is invalid.

(back to top)

Date Functions

FunctionArgumentsDescription
NowReturn seconds in epoch as for C
DatenReturn the passed in seconds as a date string
TimenReturn the passed in seconds as time on an arbitrary day
DateTimenReturn the passed in seconds as a date and time
DateSecs[y m d] Return the date in seconds in epoch

(back to top)

Random Number Generators

FunctionArgumentsDescription
SeedRandReset random sequences
UIRandnReturn a random integer between 1 and n
UDRandx yReturn a random decimal between x and y
GRandx yReturn a random decimal from a gaussian distribution with mean x and stdev y
ERandxReturn a random decimal from an exponential distribution with mean x
PRandxReturn a random integer from a poisson distribution with mean x
BRandn xReturn a random integer from a binomial distribution for n trials and probability x
GammaRanda bReturn a random decimal from an gamma distribution with shape a and rate b
WRanda bReturn a random decimal from a Weibull distribution with shape a and scale b
CRanda bReturn a random decimal from a Cauchy distribution with location a and scale b
GeoRandpReturn a random integer from a geometric distribution with probability p
NegBRandn xReturn a random integer from a negative binomial distribution for n successes and probability of success p
SobolReturn the next value in a Sobol quasi-random sequence in the range [0,1]

(back to top)

Descriptive Statistics

FunctionArgumentsDescription
Mean[z]Return the arithmetic mean of the array values
GeoMean[z]Return the geometric mean of the array values
HarMean[z]Return the harmonic mean of the array values
Median[x]Return the median of the array values
Stdev[x]Return the sample standard deviation of the array values
StdevP[x]Return the population standard deviation of the array values
MAD[x]Return the median absolute deviation from the median of the array values
Moments[x]Return the first four sample moments of the array values as a 4-array
MomentsP[x]Return the first four population moments of the array values as a 4-array
Hist[x] n|[y]Return frequency counts for the data in x binned according to [y] - either a constant number of bins, or an array holding the number of bins and the minimum and maximum values [n min max]
Range[x]Return the range of the array values as a 2-array
FivePoint[x] b1 b2Return the minimum, 1st quartile, median, 3rd quartile and maximum array values as an array. Identify and return outliers if b1 is non-zero, correcting for skew if b2 is non-zero.
Robust[x]Return the trimean, half interquartile range, and robust estimators of the skew and kurtosis of the array values
Winsorize[x] fFind points that deviate from the median by more than f * MAD, and adjust their values to f * MAD (in place)
Z[x]Convert the array values to Z scores
Ranks[x]Return an array containing the ranks for the elements of the input array
Correlation[x] [y]Return the Pearson correlation, covariance and significance for equal size array arguments
LMFit$ Do a multiple linear regression using the model described by the string argument, e.g. "f : 1 x y z", "f : a b"
Logit$Do a multiple logistic regression using the model described by the string argument. (Binary dependent data and must include constant)

(back to top)

Continuous Distributions

FunctionArgumentsDescription
StdDistxReturn pdf(x) for a standard gaussian distribution (mean 0 and stdev 1)
StdCDFxReturn cdf(x) for a standard gaussian distribution (mean 0 and stdev 1)
StdCDF2x yReturn cumulative probability for a value between x and y for a standard gaussian distribution (mean 0 and stdev 1)
StdCDFInvpReturn x such that cdf(x) = p for a standard gaussian distribution (mean 0 and stdev 1)
GDista b xReturn pdf(x) for a gaussian distribution with mean a and stdev b
GCDFa b xReturn cdf(x) for a gaussian distribution with mean a and stdev b
GCDF2a b x yReturn cumulative probability for a value between x and y for a gaussian distribution with mean a and stdev b
GCDFInva b pReturn x such that cdf(x) = p for a gaussian distribution with mean a and stdev b
EDisty xReturn pdf(x) for an exponential distribution with parameter y
ECDFy xReturn cdf(x) for an exponential distribution with parameter y
ECDFInvy pReturn x such that cdf(x) = p for an exponential distribution with parameter y
GammaDista b xReturn pdf(x) for a gamma distribution with shape a and rate b
GammaCDFa b xReturn cdf(x) for a gamma distribution with shape a and rate b
GammaCDFInva b pReturn x such that cdf(x) = p for a gamma distribution with shape a and rate b
WDista b xReturn pdf(x) for a Weibull distribution with shape a and scale b
WCDFa b xReturn cdf(x) for a Weibull distribution with shape a and scale b
WCDFInva b pReturn x such that cdf(x) = p for a Weibull distribution with shape a and scale b
CDista b xReturn pdf(x) for a Cauchy distribution with location a and scale b
CCDFa b xReturn cdf(x) for a Cauchy distribution with location a and scale b
CCDFInva b pReturn x such that cdf(x) = p for a Cauchy distribution with location a and scale b
TDistx nReturn pdf(x) for a Students t distribution with degrees of freedom n
FDistx n kReturn pdf(x) for an F distribution with degrees of freedom n and k
Chi2x nReturn pdf(x) for a Chi-squared distribution with n degrees of freedom

(back to top)

Discrete Distributions

FunctionArgumentsDescription
PDistk xReturn pdf(k) for a Poisson distribution with parameter x (probability to get k if expect x)
PCDFk xReturn cdf(k) for a Poisson distribution with parameter x (probability to get 0 to k if expect x)
PCDFInvk pReturn x such that cdf(x) = p for a Poisson distribution (to get from 0 to k with probability p means parameter x)
GeoDistk pReturn pdf(k) for a Geometric distribution with probability of success p (probability of k failures before first success)
GeoCDFk pReturn cdf(k) for a Geometric distribution with probability of success p (probability to get 0 to k failures before first success)
GeoCDFInvk xReturn probability of success p such that cdf(k) = x for a Geometric distribution
BDistk n pReturn pdf(k) for a binomial distribution with n trials and probability of success p
BCDFk n pReturn cdf(k) for a binomial distribution with n trials and probability of success p
BCDFInvPk n xReturn probability of success p such that cdf(k) = x for a binomial distribution with n trials
BCDFInvKp n xReturn number of successes given probability of success p for a binomial distribution with n trials and cdf = x
NegBDistn k pReturn pdf(k) for a negative binomial distribution with probability of n - 1 successes and k failures in k + n - 1 trials, and success on the (k + n)th trial
NegBCDFn k pReturn cdf(k) for a negative binomial distribution with n successes and n + k trials
NegBCDFInvPn k xReturn probability of success p such that cdf(k) = x for a negative binomial distribution with n successes and k failures
NegBCDFInvKp n xReturn number of failures given probability of success p for a negative binomial distribution with n successes and cdf = x

(back to top)

Statistical Tests

FunctionArgumentsDescription
ZTest[x] y sPerform a Z test using the array data, mean y and standard deviation s
T1Test[x] yPerform a one sample t-test using the array data and mean y
T2Test[x] [y]Perform an two sample t-test on the two arrays
Chi2Test[x] [y]Perform a Chi-squared test on the two arrays (observed and expected frequencies respectively)
GTest[x] [y]Perform a G-test on the two arrays (observed and expected frequencies respectively)
Chi2TestMR[x] [y] nApply a Rao-Scott multiple response correction to the Chi-squared test on the two arrays for sample size n
GTestMR[x] [y] nApply a Rao-Scott multiple response correction to the G-test on the two arrays for sample size n
FTest[x] [y]Perform an F test on the two arrays
ANOVA[[x]]Perform an ANOVA on the array of arrays
MWTest[x] [y]Perform a Mann-Whitney test on the two arrays
TestU[x]Perform an Anderson-Darling test on the array for goodness of fit to a uniform distribution.
TestG[x]Perform an Anderson-Darling test on the array for goodness of fit to a gaussian distribution.
TestDist@f [x]Perform an Anderson-Darling test on the array for goodness of fit to a distribution with CDF f(x).

(back to top)

Signal Analysis

FunctionArgumentsDescription
FFT[z]Return the Discrete Fourier Transform of the input data (no need for length a power of 2)
IFFT[z]Return the Inverse Discrete Fourier Transform of the input data
Spectrum[z]Return the Power Spectrum of the input data
Peaks[x] k hIdentify peaks in the input data, using a neighbourhood of k values and a threshold of h sigma for outlier detection
LinCorr[x] [y] bReturn the list correlation of the input vectors (auto pad with zeros - b = $1 => trim)
CycCorr[x] [y] bReturn the cyclic list correlation of the input vectors (auto pad with zeros - b = $1 => trim)
LinConv[x] [y] bReturn the list convolution of the input vectors (auto pad with zeros - b = $1 => trim)
CycConv[x] [y] bReturn the cyclic list convolution of the input vectors (auto pad with zeros - b = $1 => trim)
Fisher[x] Normalise x to (-1,1) and apply a Fisher transform

(back to top)

Polynomial

FunctionArgumentsDescription
Poly[z]Print a polynomial with coefficients as for the array z (highest order first)
PEval[z] wEvaluate the polynomial z at the point z = w
Roots[z]Calculate the roots of the polynomial z
PAdd[z] [w]Add the two polynomials
PSub[z] [w] Subtract the polynomial w from the polynomial z
PMul[z] [w] Multiply the two polynomials
PDiv[z] [w] Divide the polynomial z by the polynomial w

(back to top)

File I/O

FunctionArgumentsDescription
FOpen$ $Open a file with name given by the first argument and mode by the second, and return identifier (default white space field separation). Modes supported at "r" for reading, "w" for writing - erasing any existing content, and "a" for appending
FOpenCSV$ $Open the named csv file with modes as for FOpen and return identifier
FReadf nRead up to n rows from file f and return data as an array of arrays
FReadFldsf n [k]Read the fields specified in the sorted array [k] from up to n rows of file f and return data as an array of arrays
FWritef *Write the given data to the file f (tab or comma separated), returning the number of rows written
FClosefClose the file

(back to top)

Vectors and Matrices

FunctionArgumentsDescription
Matm n Create an m by n matrix of zeros (can access matrix elements directly using m'[r c] and rows using m'[r])
Part[*] nPartition the given array/matrix into n columns
Flatten[*] Remove any partitioning from the given matrix
IdnCreate an n by n identity matrix
Inv[z]Invert the given matrix
Trans[*]Return the transpose of the given matrix
Det[z]Calculate the determinant of the given matrix
MSolve [z] [w]Solve Z.X=W for each column in [w]
Rowi [*]Return the ith row of the matrix
Colj [*]Return the jth column of the matrix
RowSum[*]Return a column array containing the sum of each row of the matrix
ColSum[*]Return an array containing the sum of each column of the matrix
Diag[*]Return an array of the diagonal elements of the matrix
Trace[z]Return sum of the diagonal elements of the matrix
LU[z]Return the LU decomposition of the given matrix (implied unit values for the L diagonals)
RRE[z]Return the Reduced Row Echelon form of the given matrix
Rank[z]Return the rank of the given matrix
Dim[*]Return a 2-vector containing the dimensions of the matrix
Inner[z] [z]Return the inner product of the two vectors
Cross[z] [z]Return the cross product of two 3-vectors
Outer[z] [z]Return the outer product of the two vectors
RowEx[*] i jExchange rows i and j
ColEx[*] i jExchange columns i and j
RowOp[*] i j zElementary row operation: Row i += z * Row j
ColOp[*] i j zElementary col operation: Col i += z * Col j
CharP[z]Characteristic polynomial of a given square matrix
Eigenvalues[z]Eigenvalues of a given square matrix

(back to top)

Numerical Methods

FunctionArgumentsDescription
Integrate@f x y nAdaptively numerically integrate the real function f(x) from x to y starting with n steps
Solve@f x y nFind a zero in [x,y] of the function f(x) using at most n steps
Newton@f @g x nUser Newton's method to solve f(x)=0 where g(x)=f'(x)

(back to top)

Graphics

FunctionArgumentsDescription
LinePlot[x] d1 d2Plot the data in x vs their index with plot options d1 and line options d2
LinePlot2[x] [y] d1 d2Plot the data (x,y) with plot options d1 and line options d2
LinePlot3[x] [y] [z] d1 d2Plot the data (x,y,z) with plot options d1 and line options d2
FLinePlot@f [x] d1 d2Plot f x vs x for the points [x] with plot options d1 and line options d2
PlotDefsReturn a dictionary with the default box plot options preset. Available options are: title, xlabel, ylabel, zlabel, bkcolour, justify azimuth, elevation, xmin, xmax, ymin, ymax, zmin, zmax, fill, box, axis
AxesPlotDefsReturn a dictionary with the default axes plot options preset. Available options are: title, xlabel, ylabel, zlabel, bkcolour, justify azimuth, elevation, xmin, xmax, ymin, ymax, zmin, zmax, fill, box, axis
LogPlotDefsReturn a dictionary with the default box plot options and LOGX axis type
AxesLogDefsReturn a dictionary with the default axes plot options and LOGX axis type
LineDefsReturn a dictionary with the default line plot options preset. Available options are: label, colour, thickness, symbol, linestyle
SurfaceDefsReturn a dictionary with the default surface plot options preset. Available options are: label, mesh, colour, contours
Histogram[x] d1 d2Plot the counts in x as a histogram with plot options d1 and line options d2
SurfacePlot[x] [y] [z] d1 d2Plot the data z(x,y) with plot options d1 and line options d2, for x and y ordered grid points and z stored by row
FSurfacePlot@f [x] [y] d1 d2Does an Apply2D @f [x] [y] to get the [z], then as for SurfacePlot
ContourPlot[x] [y] [z] d1 d2Plot the data z(x,y) with plot options d1 and line options d2, for x and y ordered grid points and z stored by row
FContourPlot@f [x] [y] d1 d2Does an Apply2D @f [x] [y] to get the [z], then as for ContourPlot
CombineLines[a]Combine the line plots in the array into a single plot
LayoutPlots[a] iLayout the plots in the array in rows of i columns (max of 5 columns, and subplots must not already be grids)
Animate@f [a] nAnimate the function f by calling it at a rate of n times per second, using each element of a in turn as the only argument.

(back to top)

Plot Constants

FunctionDescription
linestyle:JOIN, DASH, NOLINE
mesh:MESHXY, MESHX, MESHY
character:Escape sequences for character strings: SANS = "#fn", ROMAN = "#fr", ITALIC = "#fi", SCRIPT = "#fs", GREEK = "#g" UNDER = "#-", OVER = "#+", SUB = "#d", SUPER = "#u", HASH = "##"
symbol:NOSYM, DOT, PLUS, ASTERISK, CIRCLE, CROSS, SQUARE, TRIANGLE, CIRCLEPLUS, CIRCLEDOT, CURVEDBOX, DIAMOND, STAR, SOLIDSQ, SOLIDCIRC
colour:BLACK, RED, YELLOW, GREEN, AQUAMARINE, PINK, WHEAT, GREY, BROWN, BLUE, BLUEVIOLET, CYAN, TURQUOISE, MAGENTA, SALMON, WHITE
fillSOLID, SHADED, HATCHED, NOFILL
box:NOBOX, BOX, LABELLED, AXES, GRID, AXESONLY
axis:LINEAR, LOGX, LOGY, LOGXY

(back to top)