This package implements the the Calkin-Wilf bijection between integers and rationals, as well as some convenience functions for working with rationals.
-
function N(n: number, d: number): number
Given a rational number n/d
, return its integer position in the Calkin-Wilf sequence. Negative inputs are valid, with N(-n, d) = N(n, -d) = -N(n, d)
. This function runs in logarithmic time in the size of the returned index.
-
function reduce(n: number, d: number): [number, number]
Returns an ordered pair representing the rational number n/d
in simplest form.
-
function left(n: number, d: number): [number, number]
Given a positive rational number n/d
, returns its left child in the Calkin-Wilf tree.
-
function right(n: number, d: number): [number, number]
Given a positive rational number n/d
, returns its right child in the Calkin-Wilf tree.
-
function parent(n: number, d: number): [number, number]
Given a positive rational number n/d
, returns its parent in the Calkin-Wilf tree.
-
function S(n: number, d: number): [number, number]
Given a non-negative rational number n/d
, returns its successor in the Calkin-Wilf sequence.
-
function Sd(n: number, d: number): number
Given a non-negative rational number n/d
, return the denominator of its successor in the Calkin-Wilf sequence. The numerator of the successor of n/d
is trivially equal to d
, so this function may be useful to avoid allocating memory for returning the full pair.
-
function P(n: number, d: number): [number, number]
Given a positive rational number n/d
, return its predecessor in the Calkin-Wilf sequence.
-
function Pn(n: number, d: number): number
Given a positive rational number n/d
, returns the numerator of its predecessor in the Calkin-Wilf sequence. The denominator of the predecessor of n/d
is trivially equal to n
, so this function may be useful to avoid allocating memory for returning the full pair.
-
function add(a: number, b: number, c: number, d: number): [number, number]
Returns the sum a/b + c/d
in simplest terms.
-
function sub(a: number, b: number, c: number, d: number): [number, number]
Returns the difference a/b - c/d
in simplest terms.
-
function mul(a: number, b: number, c: number, d: number): [number, number]
Returns the product (a/b)(c/d)
in simplest terms.
-
function div(a: number, b: number, c: number, d: number): [number, number]
Returns the quotient (a/b)/(c/d)
in simplest terms.
-
function cmp(a: number, b: number, c: number, d: number): -1|0|1
Compares the rational numbers a/b
and c/d
. This is more efficient than performing a full subtraction.