Core, high-performance mathematical functions and constants, specialized for primitive double and long types.
Most functions here are inlined and operate directly on primitives to avoid boxing overhead, and are primarily backed by java.lang.Math (elementary functions such as sin, cos, tan, log, sqrt), the FastMath (jafama) library (sinh, cosh, tanh, exp, hypot, rounding, and the faster, less accurate f-prefixed twins such as fsin), custom implementations for asinh, acosh and atanh, Apache Commons Math, and custom primitive implementations. Many mathematical constants (PI, E, roots, reciprocals, logarithms of common values, etc.) are also provided.
Functions and macros defined in this namespace cover:
+, -, *, /, ==, <, zero?, pos?, bit-and, bit-shift-left, etc.), including long-specific variants, fused multiply-add operations (fma, muladd, difference-of-products, sum-of-products), boolean operators (bool-xor, xor), and identity/type utilities (identity-double, identity-long, integer?).signum/sgn, and copy-sign.log1p, logsumexp, log1pexp), link functions (sigmoid, logit, logcosh, cloglog, loglog), and power functions (pow, sq, cb, fpow, mpow, tpow).floor/ceil/round variants, approximate equality, fractional part (frac, sfrac), ulp stepping (next-double, prev-double), and raw bit manipulation of doubles.lerp, constrain, norm, make-norm, wrap, smoothstep, smooth-max.slice-range, cut, co-intervals, group-by-intervals.nan?, inf?, valid-double?) and range checks (between?).gcd, lcm, agm (arithmetic-geometric mean), sample, rank, order, error calculation, and double-array conversions.Primitive Math Operators:
A set of inlined macros is provided to replace selected clojure.core arithmetic, comparison, and bitwise operators for potential performance gains with primitive arguments. These macros operate on double and long primitives and generally return primitive values.
Replaced operators:
* + - / > < >= <= == rem quot modbit-or bit-and bit-xor bit-not bit-and-notbit-shift-left bit-shift-right unsigned-bit-shift-rightbit-set bit-clear bit-flip bit-testinc deczero? neg? pos? even? odd?min maxabs<< >> >>> not== bool-notTo enable these primitive operators in your namespace, call use-primitive-operators.
To revert to the original clojure.core functions, call unuse-primitive-operators.
Note that the fastmath.core versions are not a complete drop-in replacement due to their primitive-specific behavior (e.g., return types), and calling unuse-primitive-operators at the end of the namespace is recommended, especially in Clojure 1.12+.
Core, high-performance mathematical functions and constants, specialized for primitive `double` and `long` types. Most functions here are inlined and operate directly on primitives to avoid boxing overhead, and are primarily backed by `java.lang.Math` (elementary functions such as `sin`, `cos`, `tan`, `log`, `sqrt`), the FastMath (jafama) library (`sinh`, `cosh`, `tanh`, `exp`, `hypot`, rounding, and the faster, less accurate `f`-prefixed twins such as `fsin`), custom implementations for `asinh`, `acosh` and `atanh`, Apache Commons Math, and custom primitive implementations. Many mathematical constants (`PI`, `E`, roots, reciprocals, logarithms of common values, etc.) are also provided. Functions and macros defined in this namespace cover: - Primitive-typed arithmetic, comparison, predicate and bitwise operators (`+`, `-`, `*`, `/`, `==`, `<`, `zero?`, `pos?`, `bit-and`, `bit-shift-left`, etc.), including `long`-specific variants, fused multiply-add operations (`fma`, `muladd`, `difference-of-products`, `sum-of-products`), boolean operators (`bool-xor`, `xor`), and identity/type utilities (`identity-double`, `identity-long`, `integer?`). - Trigonometric, hyperbolic, and their inverse and reciprocal functions, plus less common variants (versine, coversine, haversine, exsecant family), `signum`/`sgn`, and `copy-sign`. - Exponentials, logarithms (including numerically stable variants such as `log1p`, `logsumexp`, `log1pexp`), link functions (`sigmoid`, `logit`, `logcosh`, `cloglog`, `loglog`), and power functions (`pow`, `sq`, `cb`, `fpow`, `mpow`, `tpow`). - Combinatorics: factorials, falling/rising factorials, binomial coefficients, and Bernoulli numbers. - Rounding, truncation, and floating-point precision helpers: `floor`/`ceil`/`round` variants, approximate equality, fractional part (`frac`, `sfrac`), ulp stepping (`next-double`, `prev-double`), and raw bit manipulation of doubles. - Distance and hypotenuse calculations. - Interpolation, clamping, and range mapping: `lerp`, `constrain`, `norm`, `make-norm`, `wrap`, `smoothstep`, `smooth-max`. - Range and interval utilities: `slice-range`, `cut`, `co-intervals`, `group-by-intervals`. - Predicates for special double values (`nan?`, `inf?`, `valid-double?`) and range checks (`between?`). - Other utilities: `gcd`, `lcm`, `agm` (arithmetic-geometric mean), `sample`, `rank`, `order`, error calculation, and `double`-array conversions. Primitive Math Operators: A set of inlined macros is provided to replace selected `clojure.core` arithmetic, comparison, and bitwise operators for potential performance gains with primitive arguments. These macros operate on `double` and `long` primitives and generally return primitive values. Replaced operators: - `* + - / > < >= <= == rem quot mod` - `bit-or bit-and bit-xor bit-not bit-and-not` - `bit-shift-left bit-shift-right unsigned-bit-shift-right` - `bit-set bit-clear bit-flip bit-test` - `inc dec` - `zero? neg? pos? even? odd?` - `min max` - `abs` - Additionally: `<< >> >>> not== bool-not` To enable these primitive operators in your namespace, call [[use-primitive-operators]]. To revert to the original `clojure.core` functions, call [[unuse-primitive-operators]]. Note that the `fastmath.core` versions are not a complete drop-in replacement due to their primitive-specific behavior (e.g., return types), and calling `unuse-primitive-operators` at the end of the namespace is recommended, especially in Clojure 1.12+.
(*)(* a)(* a b)(* a b c)(* a b c d)(* a b c d & r)Multiplies numbers together. Primitive and inlined replacement for clojure.core/*.
Parameters:
double values to multiply.Returns the product as a double. With no arguments returns 1.0 (the multiplicative identity). With one argument returns it unchanged.
Note: a direct call with all-integer arguments is compiled via :inline and can return a long instead; called indirectly (apply, reduce, higher-order use), the result always follows this function's declared double signature. Value identical either way, only the type differs.
Multiplies numbers together. Primitive and inlined replacement for `clojure.core/*`. Parameters: - zero or more `double` values to multiply. Returns the product as a double. With no arguments returns `1.0` (the multiplicative identity). With one argument returns it unchanged. Note: a direct call with all-integer arguments is compiled via `:inline` and can return a `long` instead; called indirectly (`apply`, `reduce`, higher-order use), the result always follows this function's declared `double` signature. Value identical either way, only the type differs. See also [[long-mult]] (long-coerced version), [[+]], [[-]], [[/]].
(+)(+ a)(+ a b)(+ a b c)(+ a b c d)(+ a b c d & r)Adds numbers together. Primitive and inlined replacement for clojure.core/+.
Parameters:
double values to sum.Returns the sum as a double. With no arguments returns 0.0 (the additive identity). With one argument returns it unchanged.
Note: a direct call with all-integer arguments (e.g. (+ 1 2 3)) is compiled via :inline and can return a long instead. Called indirectly (apply, reduce, higher-order use), inlining does not apply and the result always follows this function's declared double signature, even for all-integer arguments. The numeric value is identical either way, only the type differs.
See also use-primitive-operators (enables this replacement), long-add (long-coerced version), -, *, /.
Adds numbers together. Primitive and inlined replacement for `clojure.core/+`. Parameters: - zero or more `double` values to sum. Returns the sum as a double. With no arguments returns `0.0` (the additive identity). With one argument returns it unchanged. Note: a direct call with all-integer arguments (e.g. `(+ 1 2 3)`) is compiled via `:inline` and can return a `long` instead. Called indirectly (`apply`, `reduce`, higher-order use), inlining does not apply and the result always follows this function's declared `double` signature, even for all-integer arguments. The numeric value is identical either way, only the type differs. See also [[use-primitive-operators]] (enables this replacement), [[long-add]] (long-coerced version), [[-]], [[*]], [[/]].
(- a)(- a b)(- a b c)(- a b c d)(- a b c d & r)Subtracts numbers, or negates a single value. Primitive and inlined replacement for clojure.core/-.
Parameters:
double values.Returns the negation of the sole argument when called with one value, otherwise the left-to-right cumulative subtraction of all arguments, as a double.
Note: a direct call with all-integer arguments is compiled via :inline and can return a long instead; called indirectly (apply, reduce, higher-order use), the result always follows this function's declared double signature. Value identical either way, only the type differs.
Subtracts numbers, or negates a single value. Primitive and inlined replacement for `clojure.core/-`. Parameters: - one or more `double` values. Returns the negation of the sole argument when called with one value, otherwise the left-to-right cumulative subtraction of all arguments, as a double. Note: a direct call with all-integer arguments is compiled via `:inline` and can return a `long` instead; called indirectly (`apply`, `reduce`, higher-order use), the result always follows this function's declared `double` signature. Value identical either way, only the type differs. See also [[long-sub]] (long-coerced version), [[+]], [[*]], [[/]].
(/ a)(/ a b)(/ a b c)(/ a b c d)(/ a b c d & r)Divides numbers, or returns the reciprocal of a single value. Primitive and inlined replacement for clojure.core//.
Parameters:
double values.Returns the reciprocal of the sole argument when called with one value, otherwise the left-to-right cumulative division of all arguments, as a double. Division by zero follows IEEE 754 semantics (returns ##Inf, ##-Inf or ##NaN, no exception thrown).
Note: a direct call with all-integer arguments is compiled via :inline and can return a long instead when the division is exact; called indirectly (apply, reduce, higher-order use), the result always follows this function's declared double signature. Value identical either way, only the type differs.
Divides numbers, or returns the reciprocal of a single value. Primitive and inlined replacement for `clojure.core//`. Parameters: - one or more `double` values. Returns the reciprocal of the sole argument when called with one value, otherwise the left-to-right cumulative division of all arguments, as a double. Division by zero follows IEEE 754 semantics (returns `##Inf`, `##-Inf` or `##NaN`, no exception thrown). Note: a direct call with all-integer arguments is compiled via `:inline` and can return a `long` instead when the division is exact; called indirectly (`apply`, `reduce`, higher-order use), the result always follows this function's declared `double` signature. Value identical either way, only the type differs. See also [[long-div]] (long-coerced version), [[+]], [[-]], [[*]].
(< _)(< a b)(< a b & r)Primitive math less-than function.
Parameters:
double values.Returns true if arguments are in strictly increasing order (chained pairwise: a<b, b<c, c<d, ...), false otherwise, as a Boolean. With one argument returns true.
Primitive math less-than function. Parameters: - one or more `double` values. Returns `true` if arguments are in strictly increasing order (chained pairwise: `a<b`, `b<c`, `c<d`, ...), `false` otherwise, as a Boolean. With one argument returns `true`. See also [[>]], [[<=]], [[>=]].
(<= _)(<= a b)(<= a b & r)Primitive math less-than-or-equal function.
Parameters:
double values.Returns true if arguments are in non-decreasing order (chained pairwise: a<=b, b<=c, c<=d, ...), false otherwise, as a Boolean. With one argument returns true.
Primitive math less-than-or-equal function. Parameters: - one or more `double` values. Returns `true` if arguments are in non-decreasing order (chained pairwise: `a<=b`, `b<=c`, `c<=d`, ...), `false` otherwise, as a Boolean. With one argument returns `true`. See also [[<]], [[>]], [[>=]].
(== _)(== a b)(== a b & r)Primitive math equality function.
Parameters:
double values.Returns true if all arguments are equal (chained pairwise: a=b, b=c, c=d, ...), false otherwise, as a Boolean. With one argument returns true.
Primitive math equality function. Parameters: - one or more `double` values. Returns `true` if all arguments are equal (chained pairwise: `a=b`, `b=c`, `c=d`, ...), `false` otherwise, as a Boolean. With one argument returns `true`. See also [[eq]] (alias), [[not==]], [[approx-eq]], [[delta-eq]].
(> _)(> a b)(> a b & r)Primitive math greater-than function.
Parameters:
double values.Returns true if arguments are in strictly decreasing order (chained pairwise: a>b, b>c, c>d, ...), false otherwise, as a Boolean. With one argument returns true.
Primitive math greater-than function. Parameters: - one or more `double` values. Returns `true` if arguments are in strictly decreasing order (chained pairwise: `a>b`, `b>c`, `c>d`, ...), `false` otherwise, as a Boolean. With one argument returns `true`. See also [[<]], [[<=]], [[>=]].
(>= _)(>= a b)(>= a b & r)Primitive math greater-than-or-equal function.
Parameters:
double values.Returns true if arguments are in non-increasing order (chained pairwise: a>=b, b>=c, c>=d, ...), false otherwise, as a Boolean. With one argument returns true.
Primitive math greater-than-or-equal function. Parameters: - one or more `double` values. Returns `true` if arguments are in non-increasing order (chained pairwise: `a>=b`, `b>=c`, `c>=d`, ...), `false` otherwise, as a Boolean. With one argument returns `true`. See also [[<]], [[>]], [[<=]].
(>> x shift)Shift bits right and keep most significant bit unchanged
Shift bits right and keep most significant bit unchanged
(>>> x shift)Shift bits right and set most significant bit to 0
Shift bits right and set most significant bit to `0`
(absolute-error v v-approx)Calculates the absolute error between a true value and an approximation.
Parameters:
v (double): the true (reference) value.v-approx (double): the approximate value.Returns (abs (- v v-approx)), i.e. the unsigned magnitude of the difference. Symmetric in its two arguments.
See also relative-error.
Calculates the absolute error between a true value and an approximation. Parameters: - `v` (double): the true (reference) value. - `v-approx` (double): the approximate value. Returns `(abs (- v v-approx))`, i.e. the unsigned magnitude of the difference. Symmetric in its two arguments. See also [[relative-error]].
(acosh x)Computes the inverse hyperbolic cosine of x, acosh(x) = log(x + sqrt(x^2 - 1)).
Parameters:
x (double): value to take the inverse hyperbolic cosine of, x >= 1.Returns acosh(x) as a double, accurate to about 2 ulps for every x >= 1, also for x close to 1 and for large x, where the direct formula loses precision or overflows. Returns 0.0 for x = 1, ##Inf for ##Inf, and ##NaN for x < 1 and for ##NaN.
Computes the inverse hyperbolic cosine of `x`, `acosh(x) = log(x + sqrt(x^2 - 1))`. Parameters: - `x` (double): value to take the inverse hyperbolic cosine of, `x >= 1`. Returns `acosh(x)` as a double, accurate to about 2 ulps for every `x >= 1`, also for `x` close to 1 and for large `x`, where the direct formula loses precision or overflows. Returns `0.0` for `x = 1`, `##Inf` for `##Inf`, and `##NaN` for `x < 1` and for `##NaN`. See also [[cosh]], [[asech]].
(acot x)Computes the inverse cotangent of x, acot(x) = π/2 - atan(x).
Parameters:
x (double): value to take the inverse cotangent of.Returns acot(x) as a double, in the range (0, π).
Computes the inverse cotangent of `x`, `acot(x) = π/2 - atan(x)`. Parameters: - `x` (double): value to take the inverse cotangent of. Returns `acot(x)` as a double, in the range `(0, π)`. See also [[atan]], [[asec]], [[acsc]].
(acoth x)Computes the area (inverse) hyperbolic cotangent of x, acoth(x) = atanh(1/x).
Parameters:
x (double): value to take the area hyperbolic cotangent of; must satisfy |x| > 1.Returns acoth(x) as a double. Returns ##NaN for |x| <= 1 (outside the domain).
Computes the area (inverse) hyperbolic cotangent of `x`, `acoth(x) = atanh(1/x)`. Parameters: - `x` (double): value to take the area hyperbolic cotangent of; must satisfy `|x| > 1`. Returns `acoth(x)` as a double. Returns `##NaN` for `|x| <= 1` (outside the domain). See also [[atanh]], [[asech]], [[acsch]].
(acovercos x)Computes the arc (inverse) covercosine of x, acovercos(x) = asin(x - 1).
Parameters:
x (double): covercosine value; must satisfy 0 <= x <= 2 for a real result.Returns the angle in radians as a double, in [-π/2, π/2]. Returns ##NaN outside the domain.
Computes the arc (inverse) covercosine of `x`, `acovercos(x) = asin(x - 1)`. Parameters: - `x` (double): covercosine value; must satisfy `0 <= x <= 2` for a real result. Returns the angle in radians as a double, in `[-π/2, π/2]`. Returns `##NaN` outside the domain. See also [[covercos]], [[acoversin]], [[avercos]].
(acoversin x)Computes the arc (inverse) coversine of x, acoversin(x) = asin(1 - x).
Parameters:
x (double): coversine value; must satisfy 0 <= x <= 2 for a real result.Returns the angle in radians as a double, in [-π/2, π/2]. Returns ##NaN outside the domain.
Computes the arc (inverse) coversine of `x`, `acoversin(x) = asin(1 - x)`. Parameters: - `x` (double): coversine value; must satisfy `0 <= x <= 2` for a real result. Returns the angle in radians as a double, in `[-π/2, π/2]`. Returns `##NaN` outside the domain. See also [[coversin]], [[aversin]], [[acovercos]].
(acrd x)Computes the inverse chord function, acrd(x) = 2*asin(x/2).
Parameters:
x (double): chord length; must satisfy |x| <= 2 for a real result.Returns the central angle in radians as a double. Returns ##NaN outside the domain.
Computes the inverse chord function, `acrd(x) = 2*asin(x/2)`. Parameters: - `x` (double): chord length; must satisfy `|x| <= 2` for a real result. Returns the central angle in radians as a double. Returns `##NaN` outside the domain. See also [[crd]], [[asin]].
(acsc x)Computes the inverse cosecant of x, acsc(x) = asin(1/x).
Parameters:
x (double): value to take the inverse cosecant of; must satisfy |x| >= 1.Returns acsc(x) as a double, in the range [-π/2, π/2]. Returns ##NaN for |x| < 1 (outside the domain).
Computes the inverse cosecant of `x`, `acsc(x) = asin(1/x)`. Parameters: - `x` (double): value to take the inverse cosecant of; must satisfy `|x| >= 1`. Returns `acsc(x)` as a double, in the range `[-π/2, π/2]`. Returns `##NaN` for `|x| < 1` (outside the domain). See also [[asin]], [[acot]], [[asec]].
(acsch v)Computes the area (inverse) hyperbolic cosecant of x, acsch(x) = asinh(1/x).
Parameters:
x (double): value to take the area hyperbolic cosecant of; must be nonzero.Returns acsch(x) as a double. Returns ##Inf/##-Inf at x=0 per IEEE 754 division semantics (1/0 = ##Inf).
Computes the area (inverse) hyperbolic cosecant of `x`, `acsch(x) = asinh(1/x)`. Parameters: - `x` (double): value to take the area hyperbolic cosecant of; must be nonzero. Returns `acsch(x)` as a double. Returns `##Inf`/`##-Inf` at `x=0` per IEEE 754 division semantics (`1/0 = ##Inf`). See also [[asinh]], [[acoth]], [[asech]].
(aexcsc x)Computes the arc (inverse) excosecant of x, aexcsc(x) = acsc(x + 1).
Parameters:
x (double): excosecant value; must satisfy x >= 0 or x <= -2 for a real result.Returns the angle in radians as a double, in [-π/2, π/2]. Returns ##NaN outside the domain.
Computes the arc (inverse) excosecant of `x`, `aexcsc(x) = acsc(x + 1)`. Parameters: - `x` (double): excosecant value; must satisfy `x >= 0` or `x <= -2` for a real result. Returns the angle in radians as a double, in `[-π/2, π/2]`. Returns `##NaN` outside the domain. See also [[excsc]], [[acsc]], [[aexsec]].
(aexsec x)Computes the arc (inverse) exsecant of x, aexsec(x) = asec(x + 1).
Parameters:
x (double): exsecant value; must satisfy x >= 0 or x <= -2 for a real result.Returns the angle in radians as a double, in [0, π]. Returns ##NaN outside the domain.
Computes the arc (inverse) exsecant of `x`, `aexsec(x) = asec(x + 1)`. Parameters: - `x` (double): exsecant value; must satisfy `x >= 0` or `x <= -2` for a real result. Returns the angle in radians as a double, in `[0, π]`. Returns `##NaN` outside the domain. See also [[exsec]], [[asec]], [[aexcsc]].
(agm x y)(agm x
y
{:keys [abs-tol rel-tol max-iters]
:or {abs-tol 1.0E-12 rel-tol 1.0E-12 max-iters 100}})Calculates the arithmetic-geometric mean (agM) of two numbers x and y.
The agM is computed iteratively: at each step the arithmetic mean and the geometric mean of the current pair replace x and y, and both sequences converge to the same limit, which is returned. This limit lies between x and y.
Parameters:
x, y (doubles): The two numbers to average.opts (map, optional): convergence options --
:abs-tol (double): Absolute tolerance used to detect convergence, i.e. x and y are considered equal (see delta-eq). Defaults to 1.0e-12.:rel-tol (double): Relative tolerance, scaled by (max (abs x) (abs y)) (see delta-eq). Defaults to 1.0e-12. Combined with :abs-tol, this keeps convergence reachable at any input magnitude, since a purely absolute tolerance can fall below a single floating-point ULP for large x/y.:max-iters (long): Maximum number of iterations allowed before giving up. Defaults to 100.Both x and y should be non-negative, since the geometric mean step involves a square root.
Returns the arithmetic-geometric mean as a double.
Throws an exception if convergence is not reached within :max-iters iterations.
Calculates the arithmetic-geometric mean (agM) of two numbers `x` and `y`. The agM is computed iteratively: at each step the arithmetic mean and the geometric mean of the current pair replace `x` and `y`, and both sequences converge to the same limit, which is returned. This limit lies between `x` and `y`. Parameters: - `x`, `y` (doubles): The two numbers to average. - `opts` (map, optional): convergence options -- - `:abs-tol` (double): Absolute tolerance used to detect convergence, i.e. `x` and `y` are considered equal (see [[delta-eq]]). Defaults to `1.0e-12`. - `:rel-tol` (double): Relative tolerance, scaled by `(max (abs x) (abs y))` (see [[delta-eq]]). Defaults to `1.0e-12`. Combined with `:abs-tol`, this keeps convergence reachable at any input magnitude, since a purely absolute tolerance can fall below a single floating-point ULP for large `x`/`y`. - `:max-iters` (long): Maximum number of iterations allowed before giving up. Defaults to `100`. Both `x` and `y` should be non-negative, since the geometric mean step involves a square root. Returns the arithmetic-geometric mean as a double. Throws an exception if convergence is not reached within `:max-iters` iterations.
(ahacovercos x)Computes the arc (inverse) hacovercosine of x, ahacovercos(x) = asin(2x - 1).
Parameters:
x (double): hacovercosine value; must satisfy 0 <= x <= 1 for a real result.Returns the angle in radians as a double, in [-π/2, π/2]. Returns ##NaN outside the domain.
See also hacovercos, ahacoversin, ahavercos.
Computes the arc (inverse) hacovercosine of `x`, `ahacovercos(x) = asin(2x - 1)`. Parameters: - `x` (double): hacovercosine value; must satisfy `0 <= x <= 1` for a real result. Returns the angle in radians as a double, in `[-π/2, π/2]`. Returns `##NaN` outside the domain. See also [[hacovercos]], [[ahacoversin]], [[ahavercos]].
(ahacoversin x)Computes the arc (inverse) hacoversine of x, ahacoversin(x) = asin(1 - 2x).
Parameters:
x (double): hacoversine value; must satisfy 0 <= x <= 1 for a real result.Returns the angle in radians as a double, in [-π/2, π/2]. Returns ##NaN outside the domain.
See also hacoversin, ahaversin, ahacovercos.
Computes the arc (inverse) hacoversine of `x`, `ahacoversin(x) = asin(1 - 2x)`. Parameters: - `x` (double): hacoversine value; must satisfy `0 <= x <= 1` for a real result. Returns the angle in radians as a double, in `[-π/2, π/2]`. Returns `##NaN` outside the domain. See also [[hacoversin]], [[ahaversin]], [[ahacovercos]].
(ahavercos x)Computes the arc (inverse) havercosine of x, ahavercos(x) = acos(2x - 1).
Parameters:
x (double): havercosine value; must satisfy 0 <= x <= 1 for a real result.Returns the angle in radians as a double, in [0, π]. Returns ##NaN outside the domain.
See also havercos, ahaversin, ahacovercos.
Computes the arc (inverse) havercosine of `x`, `ahavercos(x) = acos(2x - 1)`. Parameters: - `x` (double): havercosine value; must satisfy `0 <= x <= 1` for a real result. Returns the angle in radians as a double, in `[0, π]`. Returns `##NaN` outside the domain. See also [[havercos]], [[ahaversin]], [[ahacovercos]].
(ahaversin x)Computes the arc (inverse) haversine of x, ahaversin(x) = acos(1 - 2x).
Parameters:
x (double): haversine value; must satisfy 0 <= x <= 1 for a real result.Returns the angle in radians as a double, in [0, π]. Returns ##NaN outside the domain.
See also haversin, ahacoversin, ahavercos.
Computes the arc (inverse) haversine of `x`, `ahaversin(x) = acos(1 - 2x)`. Parameters: - `x` (double): haversine value; must satisfy `0 <= x <= 1` for a real result. Returns the angle in radians as a double, in `[0, π]`. Returns `##NaN` outside the domain. See also [[haversin]], [[ahacoversin]], [[ahavercos]].
(approx v)(approx v digits)Rounds v to a given number of decimal places, half-up.
Parameters:
v (double): the number to round.digits (long, optional, default 2): number of decimal places to keep. 0 rounds to the nearest integer; negative values round to the nearest multiple of a power of ten (e.g. -1 rounds to the nearest 10).Returns the rounded value as a double.
Rounds `v` to a given number of decimal places, half-up. Parameters: - `v` (double): the number to round. - `digits` (long, optional, default `2`): number of decimal places to keep. `0` rounds to the nearest integer; negative values round to the nearest multiple of a power of ten (e.g. `-1` rounds to the nearest 10). Returns the rounded value as a double. See also [[approx-eq]], [[delta-eq]].
(approx-eq a b)(approx-eq a b digits)Checks whether a and b round to the same value at a given number of decimal places.
Parameters:
a, b (doubles): the two numbers to compare.digits (long, optional, default 2): number of decimal places used for rounding (see approx).Returns true if (== a b), or if approx of a and b are equal at the given number of digits. Returns false otherwise.
This equality check can be inaccurate near a rounding boundary: 1.004999 and 1.005001 differ by only 0.000002 but round to 1.0 and 1.01 respectively at 2 digits, so approx-eq reports them as unequal -- prefer delta-eq for a tolerance-based comparison.
Checks whether `a` and `b` round to the same value at a given number of decimal places. Parameters: - `a`, `b` (doubles): the two numbers to compare. - `digits` (long, optional, default `2`): number of decimal places used for rounding (see [[approx]]). Returns `true` if `(== a b)`, or if [[approx]] of `a` and `b` are equal at the given number of digits. Returns `false` otherwise. This equality check can be inaccurate near a rounding boundary: `1.004999` and `1.005001` differ by only `0.000002` but round to `1.0` and `1.01` respectively at 2 digits, so `approx-eq` reports them as unequal -- prefer [[delta-eq]] for a tolerance-based comparison. See also [[approx]], [[delta-eq]].
(asec x)Computes the inverse secant of x, asec(x) = acos(1/x).
Parameters:
x (double): value to take the inverse secant of; must satisfy |x| >= 1.Returns asec(x) as a double, in the range [0, π]. Returns ##NaN for |x| < 1 (outside the domain).
Computes the inverse secant of `x`, `asec(x) = acos(1/x)`. Parameters: - `x` (double): value to take the inverse secant of; must satisfy `|x| >= 1`. Returns `asec(x)` as a double, in the range `[0, π]`. Returns `##NaN` for `|x| < 1` (outside the domain). See also [[acos]], [[acot]], [[acsc]].
(asech x)Computes the area (inverse) hyperbolic secant of x, asech(x) = acosh(1/x).
Parameters:
x (double): value to take the area hyperbolic secant of; must satisfy 0 < x <= 1.Returns asech(x) as a double, always non-negative. Returns ##NaN outside the domain.
Computes the area (inverse) hyperbolic secant of `x`, `asech(x) = acosh(1/x)`. Parameters: - `x` (double): value to take the area hyperbolic secant of; must satisfy `0 < x <= 1`. Returns `asech(x)` as a double, always non-negative. Returns `##NaN` outside the domain. See also [[acosh]], [[acoth]], [[acsch]].
(asinh x)Computes the inverse hyperbolic sine of x, asinh(x) = log(x + sqrt(x^2 + 1)).
Parameters:
x (double): value to take the inverse hyperbolic sine of.Returns asinh(x) as a double, accurate to about 2 ulps for every x, also for x close to zero and for large |x|, where the direct formula loses precision or overflows. It is an odd function: asinh(-x) = -asinh(x). Returns x for 0.0 and -0.0 (the sign of a zero is kept), ##Inf or ##-Inf for an infinite x, and ##NaN for ##NaN.
Computes the inverse hyperbolic sine of `x`, `asinh(x) = log(x + sqrt(x^2 + 1))`. Parameters: - `x` (double): value to take the inverse hyperbolic sine of. Returns `asinh(x)` as a double, accurate to about 2 ulps for every `x`, also for `x` close to zero and for large `|x|`, where the direct formula loses precision or overflows. It is an odd function: `asinh(-x) = -asinh(x)`. Returns `x` for `0.0` and `-0.0` (the sign of a zero is kept), `##Inf` or `##-Inf` for an infinite `x`, and `##NaN` for `##NaN`. See also [[sinh]], [[acsch]].
(atanh x)Computes the inverse hyperbolic tangent of x, atanh(x) = 0.5 * log((1 + x) / (1 - x)).
Parameters:
x (double): value to take the inverse hyperbolic tangent of, -1 <= x <= 1.Returns atanh(x) as a double, accurate to about 2 ulps for every x in the domain, also for x close to zero and close to 1 or -1. It is an odd function: atanh(-x) = -atanh(x). Returns x for 0.0 and -0.0 (the sign of a zero is kept), ##Inf for x = 1, ##-Inf for x = -1, and ##NaN for |x| > 1 and for ##NaN.
Computes the inverse hyperbolic tangent of `x`, `atanh(x) = 0.5 * log((1 + x) / (1 - x))`. Parameters: - `x` (double): value to take the inverse hyperbolic tangent of, `-1 <= x <= 1`. Returns `atanh(x)` as a double, accurate to about 2 ulps for every `x` in the domain, also for `x` close to zero and close to `1` or `-1`. It is an odd function: `atanh(-x) = -atanh(x)`. Returns `x` for `0.0` and `-0.0` (the sign of a zero is kept), `##Inf` for `x = 1`, `##-Inf` for `x = -1`, and `##NaN` for `|x| > 1` and for `##NaN`. See also [[tanh]], [[acoth]].
(avercos x)Computes the arc (inverse) vercosine of x, avercos(x) = acos(x - 1).
Parameters:
x (double): vercosine value; must satisfy 0 <= x <= 2 for a real result.Returns the angle in radians as a double, in [0, π]. Returns ##NaN outside the domain.
Computes the arc (inverse) vercosine of `x`, `avercos(x) = acos(x - 1)`. Parameters: - `x` (double): vercosine value; must satisfy `0 <= x <= 2` for a real result. Returns the angle in radians as a double, in `[0, π]`. Returns `##NaN` outside the domain. See also [[vercos]], [[aversin]], [[acovercos]].
(aversin x)Computes the arc (inverse) versine of x, aversin(x) = acos(1 - x).
Parameters:
x (double): versine value; must satisfy 0 <= x <= 2 for a real result.Returns the angle in radians as a double, in [0, π]. Returns ##NaN outside the domain.
Computes the arc (inverse) versine of `x`, `aversin(x) = acos(1 - x)`. Parameters: - `x` (double): versine value; must satisfy `0 <= x <= 2` for a real result. Returns the angle in radians as a double, in `[0, π]`. Returns `##NaN` outside the domain. See also [[versin]], [[acoversin]], [[avercos]].
(bernoulli n)Calculates the n-th Bernoulli number, B_n.
This implementation uses the B_1 = +1/2 sign convention, giving the sequence B_0 = 1, B_1 = 1/2, B_2 = 1/6, B_3 = 0, B_4 = -1/30, and so on.
Parameters:
n (long): Index of the Bernoulli number to compute, must be non-negative.Returns B_n as a double. All odd-indexed Bernoulli numbers above B_1 (i.e. B_3, B_5, B_7, ...) are 0.0.
See also factorial.
Calculates the `n`-th Bernoulli number, `B_n`. This implementation uses the `B_1 = +1/2` sign convention, giving the sequence `B_0 = 1`, `B_1 = 1/2`, `B_2 = 1/6`, `B_3 = 0`, `B_4 = -1/30`, and so on. Parameters: - `n` (long): Index of the Bernoulli number to compute, must be non-negative. Returns `B_n` as a double. All odd-indexed Bernoulli numbers above `B_1` (i.e. `B_3`, `B_5`, `B_7`, ...) are `0.0`. See also [[factorial]].
(between-? [x y] v)(between-? x y v)Checks whether v lies within the half-open range (x,y].
Parameters:
[x y] (sequence of two doubles), v (double): range as a pair, plus the value to check.x, y, v (doubles): range bounds and the value to check, given directly.Returns true if x<v<=y (x itself excluded, y included), false otherwise.
Checks whether `v` lies within the half-open range `(x,y]`. Parameters: - `[x y]` (sequence of two doubles), `v` (double): range as a pair, plus the value to check. - `x`, `y`, `v` (doubles): range bounds and the value to check, given directly. Returns `true` if `x<v<=y` (`x` itself excluded, `y` included), `false` otherwise. See also [[between?]] (closed range), [[constrain]].
(between? [x y] v)(between? x y v)Checks whether v lies within the closed range [x,y].
Parameters:
[x y] (sequence of two doubles), v (double): range as a pair, plus the value to check.x, y, v (doubles): range bounds and the value to check, given directly.Returns true if x<=v<=y, false otherwise -- including when x>y (an inverted range is never satisfiable, not auto-swapped) or when v is NaN (every comparison with NaN is false).
Checks whether `v` lies within the closed range `[x,y]`. Parameters: - `[x y]` (sequence of two doubles), `v` (double): range as a pair, plus the value to check. - `x`, `y`, `v` (doubles): range bounds and the value to check, given directly. Returns `true` if `x<=v<=y`, `false` otherwise -- including when `x>y` (an inverted range is never satisfiable, not auto-swapped) or when `v` is `NaN` (every comparison with `NaN` is `false`). See also [[between-?]] (half-open range), [[constrain]].
(bit-and x)(bit-and x y)(bit-and x y & r)Bitwise AND (x ∧ y) of two or more integer values.
Parameters:
long.Returns the bitwise AND of all arguments as a long, computed by folding pairwise from left to right. With one argument returns it unchanged.
See also bit-or, bit-xor, bit-and-not, bit-nand.
Bitwise AND (`x ∧ y`) of two or more integer values. Parameters: - one or more values coercible to `long`. Returns the bitwise AND of all arguments as a long, computed by folding pairwise from left to right. With one argument returns it unchanged. See also [[bit-or]], [[bit-xor]], [[bit-and-not]], [[bit-nand]].
(bit-and-not x)(bit-and-not x y)(bit-and-not x y & r)Bitwise AND with complemented subsequent arguments (x ∧ ~y), folded left to right for more than two arguments.
Parameters:
long.Returns x with all bits set in any of y, z, ... cleared, as a long, computed by folding pairwise from left to right ((x and-not y) and-not z ...). With one argument returns it unchanged.
Bitwise AND with complemented subsequent arguments (`x ∧ ~y`), folded left to right for more than two arguments. Parameters: - one or more values coercible to `long`. Returns `x` with all bits set in any of `y, z, ...` cleared, as a long, computed by folding pairwise from left to right (`(x and-not y) and-not z ...`). With one argument returns it unchanged. See also [[bit-and]], [[bit-clear]].
(bit-count x)Counts the number of set (1) bits in x.
Parameters:
x (long): the value to inspect.Returns the population count as a long. Note: a direct call is compiled via :inline and returns a boxed Integer (from Long/bitCount's native int result); called indirectly (apply, higher-order use), returns a boxed Long. Value identical either way, only the box type differs.
Counts the number of set (1) bits in `x`. Parameters: - `x` (long): the value to inspect. Returns the population count as a `long`. Note: a direct call is compiled via `:inline` and returns a boxed `Integer` (from `Long/bitCount`'s native `int` result); called indirectly (`apply`, higher-order use), returns a boxed `Long`. Value identical either way, only the box type differs.
(bit-flip x bit)Flip bit (set to 0 when 1 or to 1 when 0).
Flip bit (set to `0` when `1` or to `1` when `0`).
(bit-nand x)(bit-nand x y)(bit-nand x y & r)Bitwise NAND (~(x ∧ y)) of two values, or a left-to-right pairwise fold of NAND over more than two.
Parameters:
long.Returns the bitwise NAND as a long. For three or more arguments, computes (x nand y) nand z ... -- a repeated pairwise fold, not the hardware-style ~(x ∧ y ∧ z ...) multi-input NAND. With one argument returns it unchanged.
Bitwise NAND (`~(x ∧ y)`) of two values, or a left-to-right pairwise fold of NAND over more than two. Parameters: - one or more values coercible to `long`. Returns the bitwise NAND as a long. For three or more arguments, computes `(x nand y) nand z ...` -- a repeated pairwise fold, not the hardware-style `~(x ∧ y ∧ z ...)` multi-input NAND. With one argument returns it unchanged. See also [[bit-and]], [[bit-nor]], [[bit-xnor]].
(bit-nor x)(bit-nor x y)(bit-nor x y & r)Bitwise NOR (~(x ∨ y)) of two values, or a left-to-right pairwise fold of NOR over more than two.
Parameters:
long.Returns the bitwise NOR as a long. For three or more arguments, computes (x nor y) nor z ... -- a repeated pairwise fold, not the hardware-style ~(x ∨ y ∨ z ...) multi-input NOR. With one argument returns it unchanged.
Bitwise NOR (`~(x ∨ y)`) of two values, or a left-to-right pairwise fold of NOR over more than two. Parameters: - one or more values coercible to `long`. Returns the bitwise NOR as a long. For three or more arguments, computes `(x nor y) nor z ...` -- a repeated pairwise fold, not the hardware-style `~(x ∨ y ∨ z ...)` multi-input NOR. With one argument returns it unchanged. See also [[bit-or]], [[bit-nand]], [[bit-xnor]].
(bit-or x)(bit-or x y)(bit-or x y & r)Bitwise OR (x ∨ y) of two or more integer values.
Parameters:
long.Returns the bitwise OR of all arguments as a long, computed by folding pairwise from left to right. With one argument returns it unchanged.
Bitwise OR (`x ∨ y`) of two or more integer values. Parameters: - one or more values coercible to `long`. Returns the bitwise OR of all arguments as a long, computed by folding pairwise from left to right. With one argument returns it unchanged. See also [[bit-and]], [[bit-xor]], [[bit-nor]].
(bit-shift-right x shift)Shift bits right and keep most significant bit unchanged
Shift bits right and keep most significant bit unchanged
(bit-test x bit)Test bit (return to true when 1 or false when 0).
Test bit (return to `true` when `1` or `false` when `0`).
(bit-xnor x)(bit-xnor x y)(bit-xnor x y & r)Bitwise XNOR (~(x⊕y)) of two values, or a left-to-right pairwise fold of XNOR over more than two.
Parameters:
long.Returns the bitwise XNOR as a long. For three or more arguments, computes (x xnor y) xnor z ... -- a repeated pairwise fold, not the hardware-style ~(x⊕y⊕z...) multi-input XNOR. With one argument returns it unchanged.
Bitwise XNOR (`~(x⊕y)`) of two values, or a left-to-right pairwise fold of XNOR over more than two. Parameters: - one or more values coercible to `long`. Returns the bitwise XNOR as a long. For three or more arguments, computes `(x xnor y) xnor z ...` -- a repeated pairwise fold, not the hardware-style `~(x⊕y⊕z...)` multi-input XNOR. With one argument returns it unchanged. See also [[bit-xor]], [[bit-nand]], [[bit-nor]].
(bit-xor x)(bit-xor x y)(bit-xor x y & r)Bitwise XOR (x⊕y) of two or more integer values.
Parameters:
long.Returns the bitwise XOR of all arguments as a long, computed by folding pairwise from left to right (associative, so fold order does not affect the result). With one argument returns it unchanged.
Bitwise XOR (`x⊕y`) of two or more integer values. Parameters: - one or more values coercible to `long`. Returns the bitwise XOR of all arguments as a long, computed by folding pairwise from left to right (associative, so fold order does not affect the result). With one argument returns it unchanged. See also [[bit-xnor]], [[bit-and]], [[bit-or]].
(bool-xor x y)(bool-xor x y & r)Primitive boolean XOR of two or more values.
Parameters:
Returns the exclusive-or of all arguments as a Boolean, computed by folding pairwise from left to right (associative, so fold order does not affect the result).
Primitive boolean XOR of two or more values. Parameters: - two or more values (coerced to boolean). Returns the exclusive-or of all arguments as a Boolean, computed by folding pairwise from left to right (associative, so fold order does not affect the result). See also [[xor]] (identical implementation), [[bool-not]].
(cb x)Computes x^3 (x*x*x).
Parameters:
x (double): value to cube.Returns the result as a double.
Computes `x^3` (`x*x*x`). Parameters: - `x` (double): value to cube. Returns the result as a double. See also [[pow3]] (identical implementation), [[sq]], [[pow]].
(ceil x)(ceil x scale)Rounds x towards positive infinity.
Parameters:
x (double): the number to round.scale (double, optional): if given, x is divided by scale, ceiled, then multiplied back by scale -- i.e. rounds to the nearest multiple of scale towards positive infinity.Returns the rounded value as a double.
Rounds `x` towards positive infinity. Parameters: - `x` (double): the number to round. - `scale` (double, optional): if given, `x` is divided by `scale`, ceiled, then multiplied back by `scale` -- i.e. rounds to the nearest multiple of `scale` towards positive infinity. Returns the rounded value as a double. See also [[floor]], [[round]], [[qceil]].
(cexpexp x)Computes 1 - exp(-exp(x)), the complementary Gumbel CDF form.
Parameters:
x (double): value.Returns the result as a double, always in [0, 1].
See also expexp.
Computes `1 - exp(-exp(x))`, the complementary Gumbel CDF form. Parameters: - `x` (double): value. Returns the result as a double, always in `[0, 1]`. See also [[expexp]].
(cloglog x)Computes the complementary log-log function, cloglog(x) = log(-log(1-x)), used as a link function for binary/count models.
Parameters:
x (double): probability-like value; must satisfy 0 < x < 1 for a real result.Returns the result as a double.
See also loglog.
Computes the complementary log-log function, `cloglog(x) = log(-log(1-x))`, used as a link function for binary/count models. Parameters: - `x` (double): probability-like value; must satisfy `0 < x < 1` for a real result. Returns the result as a double. See also [[loglog]].
(cnorm v start stop)(cnorm v start1 stop1 start2 stop2)Constrained (clamped) version of norm.
Parameters: same as norm -- v, start, stop for the 3-arity form (maps and clamps to [0,1]); v, start1, stop1, start2, stop2 for the 5-arity form (maps and clamps to [start2,stop2]).
Returns the result of norm clamped (constrain) to the target range, so it never extrapolates outside it even when v lies outside the source range.
Constrained (clamped) version of [[norm]]. Parameters: same as [[norm]] -- `v`, `start`, `stop` for the 3-arity form (maps and clamps to `[0,1]`); `v`, `start1`, `stop1`, `start2`, `stop2` for the 5-arity form (maps and clamps to `[start2,stop2]`). Returns the result of [[norm]] clamped ([[constrain]]) to the target range, so it never extrapolates outside it even when `v` lies outside the source range. See also [[norm]], [[constrain]].
(co-intervals data)(co-intervals data number)(co-intervals data number overlap)Divides data into number overlapping intervals, each containing a similar count of values.
Unlike cut, which produces equally spaced intervals, this function determines interval boundaries from the sorted data itself so that every interval covers roughly the same number of observations, with consecutive intervals overlapping by a given proportion. This replicates the behaviour of R's co.intervals() function. Non-finite values (NaN, infinities) are removed from data before processing.
Parameters:
data (sequence of numbers): Values to partition.number (long): Desired number of intervals. Defaults to 6.overlap (double): Desired overlap proportion between consecutive intervals, in range [0.0, 1.0]. Defaults to 0.5.Returns a sequence of intervals, each represented as a 2-element vector [lower-bound upper-bound]. The resulting number of intervals may be smaller than number when the data does not support that many distinct overlapping groups.
See also cut, group-by-intervals.
Divides `data` into `number` overlapping intervals, each containing a similar count of values. Unlike [[cut]], which produces equally spaced intervals, this function determines interval boundaries from the sorted data itself so that every interval covers roughly the same number of observations, with consecutive intervals overlapping by a given proportion. This replicates the behaviour of R's `co.intervals()` function. Non-finite values (`NaN`, infinities) are removed from `data` before processing. Parameters: - `data` (sequence of numbers): Values to partition. - `number` (long): Desired number of intervals. Defaults to `6`. - `overlap` (double): Desired overlap proportion between consecutive intervals, in range `[0.0, 1.0]`. Defaults to `0.5`. Returns a sequence of intervals, each represented as a 2-element vector `[lower-bound upper-bound]`. The resulting number of intervals may be smaller than `number` when the data does not support that many distinct overlapping groups. See also [[cut]], [[group-by-intervals]].
(combinations n k)Computes the binomial coefficient, n choose k.
Parameters:
n (long): total number of items.k (long): number of items to choose.Returns the binomial coefficient as a double, 0.0 when k is negative or greater than n. Uses a direct iterative product for k < 30, and a log-beta-based formula for larger k to avoid overflow.
See also log-combinations, falling-factorial.
Computes the binomial coefficient, `n choose k`. Parameters: - `n` (long): total number of items. - `k` (long): number of items to choose. Returns the binomial coefficient as a double, `0.0` when `k` is negative or greater than `n`. Uses a direct iterative product for `k < 30`, and a log-beta-based formula for larger `k` to avoid overflow. See also [[log-combinations]], [[falling-factorial]].
(constrain value mn mx)Clamps value to the closed range [mn,mx].
Parameters:
value: the value to clamp.mn, mx: the lower and upper bounds.Returns value if it already lies within [mn,mx], otherwise the nearer of the two bounds. If mn>mx (an inverted range), always returns mn regardless of value -- the bounds are not validated or auto-swapped.
Clamps `value` to the closed range `[mn,mx]`. Parameters: - `value`: the value to clamp. - `mn`, `mx`: the lower and upper bounds. Returns `value` if it already lies within `[mn,mx]`, otherwise the nearer of the two bounds. If `mn>mx` (an inverted range), always returns `mn` regardless of `value` -- the bounds are not validated or auto-swapped. See also [[cnorm]] (constrains the result of [[norm]]).
(copy-sign magnitude sign)Returns a value with a magnitude of first argument and sign of second.
Returns a value with a magnitude of first argument and sign of second.
(cos-interpolation start stop t)Interpolates between start and stop following a cosine ease curve, for amount t.
Parameters:
start, stop (doubles): the two endpoints.t (double): interpolation amount, typically in [0,1].Returns start when t=0, stop when t=1, easing smoothly (zero slope at both ends) rather than linearly in between, via 0.5*(1-cos(t*PI)) as the effective interpolation amount.
See also lerp/mlerp (linear), quad-interpolation, smooth-interpolation (other easing curves).
Interpolates between `start` and `stop` following a cosine ease curve, for amount `t`. Parameters: - `start`, `stop` (doubles): the two endpoints. - `t` (double): interpolation amount, typically in `[0,1]`. Returns `start` when `t=0`, `stop` when `t=1`, easing smoothly (zero slope at both ends) rather than linearly in between, via `0.5*(1-cos(t*PI))` as the effective interpolation amount. See also [[lerp]]/[[mlerp]] (linear), [[quad-interpolation]], [[smooth-interpolation]] (other easing curves).
(cospi x)Computes cos(π·x) -- the cosine of x expressed in half-turns (units of π) rather than radians.
The argument is reduced exactly to the nearest integer before the cosine is taken, so the result is accurate to about 1 ulp for any x (also next to its zeros), the error does not grow with |x|, and the identity values are exact.
Parameters:
x (double): value in half-turns to take the cosine of.Returns cos(π·x) as a double. At every half-integer x the result is +0.0 (the function is even), at integers it is exactly 1.0 or -1.0. Infinite or NaN x gives ##NaN.
Computes `cos(π·x)` -- the cosine of `x` expressed in half-turns (units of π) rather than radians. The argument is reduced exactly to the nearest integer before the cosine is taken, so the result is accurate to about 1 ulp for any `x` (also next to its zeros), the error does not grow with `|x|`, and the identity values are exact. Parameters: - `x` (double): value in half-turns to take the cosine of. Returns `cos(π·x)` as a double. At every half-integer `x` the result is `+0.0` (the function is even), at integers it is exactly `1.0` or `-1.0`. Infinite or NaN `x` gives `##NaN`. See also [[cos]], [[sinpi]], [[tanpi]], [[secpi]].
(cot x)Computes the cotangent of x, cot(x) = 1/tan(x).
Parameters:
x (double): angle in radians.Returns cot(x) as a double. Diverges where tan(x) is zero, i.e. at integer multiples of π.
Computes the cotangent of `x`, `cot(x) = 1/tan(x)`. Parameters: - `x` (double): angle in radians. Returns `cot(x)` as a double. Diverges where `tan(x)` is zero, i.e. at integer multiples of π. See also [[tan]], [[cotpi]], [[sec]], [[csc]].
(coth x)Computes the hyperbolic cotangent of x, coth(x) = 1/tanh(x).
Parameters:
x (double): value to take the hyperbolic cotangent of.Returns coth(x) as a double. Diverges at x=0 (where tanh(x) is zero).
Computes the hyperbolic cotangent of `x`, `coth(x) = 1/tanh(x)`. Parameters: - `x` (double): value to take the hyperbolic cotangent of. Returns `coth(x)` as a double. Diverges at `x=0` (where `tanh(x)` is zero). See also [[tanh]], [[sech]], [[csch]].
(cotpi x)Computes the cotangent of x expressed in half-turns (units of π), cot(π·x) = 1/tan(π·x).
Parameters:
x (double): value in half-turns.Returns cot(π·x) as a double, the reciprocal of tanpi: ##Inf or ##-Inf at an integer x, a signed zero at a half-integer x. Infinite or NaN x gives ##NaN.
Computes the cotangent of `x` expressed in half-turns (units of π), `cot(π·x) = 1/tan(π·x)`. Parameters: - `x` (double): value in half-turns. Returns `cot(π·x)` as a double, the reciprocal of [[tanpi]]: `##Inf` or `##-Inf` at an integer `x`, a signed zero at a half-integer `x`. Infinite or NaN `x` gives `##NaN`. See also [[cot]], [[tanpi]], [[secpi]], [[cscpi]].
(covercos x)Computes the covercosine (coversed cosine) of x, covercos(x) = 1 + sin(x).
Parameters:
x (double): angle in radians.Returns the covercosine as a double, always in [0, 2].
Computes the covercosine (coversed cosine) of `x`, `covercos(x) = 1 + sin(x)`. Parameters: - `x` (double): angle in radians. Returns the covercosine as a double, always in `[0, 2]`. See also [[acovercos]], [[coversin]], [[vercos]].
(coversin x)Computes the coversine (coversed sine) of x, coversin(x) = 1 - sin(x).
Parameters:
x (double): angle in radians.Returns the coversine as a double, always in [0, 2].
Computes the coversine (coversed sine) of `x`, `coversin(x) = 1 - sin(x)`. Parameters: - `x` (double): angle in radians. Returns the coversine as a double, always in `[0, 2]`. See also [[acoversin]], [[versin]], [[covercos]].
(crd x)Computes the chord length of an arc, crd(x) = 2*sin(x/2), for a unit circle.
Parameters:
x (double): central angle in radians.Returns the chord length as a double.
Computes the chord length of an arc, `crd(x) = 2*sin(x/2)`, for a unit circle. Parameters: - `x` (double): central angle in radians. Returns the chord length as a double. See also [[acrd]], [[sin]].
(csc x)Computes the cosecant of x, csc(x) = 1/sin(x).
Parameters:
x (double): angle in radians.Returns csc(x) as a double. Diverges where sin(x) is zero, i.e. at integer multiples of π.
Computes the cosecant of `x`, `csc(x) = 1/sin(x)`. Parameters: - `x` (double): angle in radians. Returns `csc(x)` as a double. Diverges where `sin(x)` is zero, i.e. at integer multiples of π. See also [[sin]], [[cscpi]], [[cot]], [[sec]].
(csch x)Computes the hyperbolic cosecant of x, csch(x) = 1/sinh(x).
Parameters:
x (double): value to take the hyperbolic cosecant of.Returns csch(x) as a double. Diverges at x=0 (where sinh(x) is zero).
Computes the hyperbolic cosecant of `x`, `csch(x) = 1/sinh(x)`. Parameters: - `x` (double): value to take the hyperbolic cosecant of. Returns `csch(x)` as a double. Diverges at `x=0` (where `sinh(x)` is zero). See also [[sinh]], [[coth]], [[sech]].
(cscpi x)Computes the cosecant of x expressed in half-turns (units of π), csc(π·x) = 1/sin(π·x).
Parameters:
x (double): value in half-turns.Returns csc(π·x) as a double, the reciprocal of sinpi: ##Inf or ##-Inf (the sign of x) at an integer x. Infinite or NaN x gives ##NaN.
Computes the cosecant of `x` expressed in half-turns (units of π), `csc(π·x) = 1/sin(π·x)`. Parameters: - `x` (double): value in half-turns. Returns `csc(π·x)` as a double, the reciprocal of [[sinpi]]: `##Inf` or `##-Inf` (the sign of `x`) at an integer `x`. Infinite or NaN `x` gives `##NaN`. See also [[csc]], [[sinpi]], [[cotpi]], [[secpi]].
(cut data breaks)(cut x1 x2 breaks)Divides a numerical range into breaks equally spaced, half-open intervals.
The function first generates breaks + 1 equally spaced boundary points across the range using slice-range, then pairs consecutive points into intervals. Each interval is closed on the right, i.e. (lower, upper], so that every value in the range falls into exactly one interval. The lower bound of the very first interval is nudged one ulp downwards (via prev-double) so that the exact minimum of the range is included too.
Parameters:
[data breaks] (sequence, long): The range is [(min data), (max data)]. Non-finite values (NaN, infinities) are removed from data before computing the range.[x1 x2 breaks] (double, double, long): Explicit range [x1, x2].breaks (long): Desired number of intervals, must be positive.Returns a sequence of breaks 2-element vectors [lower-bound upper-bound].
See also slice-range, co-intervals.
Divides a numerical range into `breaks` equally spaced, half-open intervals. The function first generates `breaks + 1` equally spaced boundary points across the range using [[slice-range]], then pairs consecutive points into intervals. Each interval is closed on the right, i.e. `(lower, upper]`, so that every value in the range falls into exactly one interval. The lower bound of the very first interval is nudged one ulp downwards (via [[prev-double]]) so that the exact minimum of the range is included too. Parameters: - `[data breaks]` (sequence, long): The range is `[(min data), (max data)]`. Non-finite values (`NaN`, infinities) are removed from `data` before computing the range. - `[x1 x2 breaks]` (double, double, long): Explicit range `[x1, x2]`. - `breaks` (long): Desired number of intervals, must be positive. Returns a sequence of `breaks` 2-element vectors `[lower-bound upper-bound]`. See also [[slice-range]], [[co-intervals]].
(dec x)Primitive and inlined dec. A direct call with an integer argument can return a long via :inline; called indirectly (apply, higher-order use), always returns a double (same value, see +).
Primitive and inlined `dec`. A direct call with an integer argument can return a `long` via `:inline`; called indirectly (`apply`, higher-order use), always returns a `double` (same value, see [[+]]).
(degrees rad)Converts an angle from radians to degrees.
Parameters:
rad (double): angle in radians.Returns the angle in degrees as a double.
See also radians.
Converts an angle from radians to degrees. Parameters: - `rad` (double): angle in radians. Returns the angle in degrees as a double. See also [[radians]].
(delta-eq a b)(delta-eq a b accuracy)(delta-eq a b abs-tol rel-tol)Checks if two floating-point numbers a and b are approximately equal within given tolerances.
The check returns true if abs(a - b) is less than a combined tolerance, or if (== a b).
(delta-eq a b): Uses a default absolute tolerance of 1.0e-6.(delta-eq a b abs-tol): Uses the provided absolute tolerance abs-tol.(delta-eq a b abs-tol rel-tol): Uses both absolute and relative tolerances. The combined tolerance is max(abs-tol, rel-tol * max(abs(a), abs(b))).This function is useful for comparing floating-point numbers where exact equality checks (==) may fail due to precision issues.
Checks if two floating-point numbers `a` and `b` are approximately equal within given tolerances. The check returns true if `abs(a - b)` is less than a combined tolerance, or if `(== a b)`. - 2-arity `(delta-eq a b)`: Uses a default absolute tolerance of `1.0e-6`. - 3-arity `(delta-eq a b abs-tol)`: Uses the provided absolute tolerance `abs-tol`. - 4-arity `(delta-eq a b abs-tol rel-tol)`: Uses both absolute and relative tolerances. The combined tolerance is `max(abs-tol, rel-tol * max(abs(a), abs(b)))`. This function is useful for comparing floating-point numbers where exact equality checks (`==`) may fail due to precision issues.
(difference-of-products a b c d)Computes a*b - c*d using Kahan's two-product algorithm to avoid catastrophic cancellation when a*b and c*d are close in magnitude.
Parameters:
a, b, c, d (doubles): factors of the two products.Returns a*b - c*d as a double, computed via two fused multiply-adds plus a correction term rather than a direct subtraction of two separately-rounded products. This achieves near full double precision even when the naive (- (* a b) (* c d)) loses many significant digits to cancellation. Requires a true hardware/JVM fused multiply-add (Java 9+) to realize the accuracy benefit; on earlier JVMs it is numerically equivalent to the naive computation.
See also sum-of-products, fma.
Computes `a*b - c*d` using Kahan's two-product algorithm to avoid catastrophic cancellation when `a*b` and `c*d` are close in magnitude. Parameters: - `a`, `b`, `c`, `d` (doubles): factors of the two products. Returns `a*b - c*d` as a double, computed via two fused multiply-adds plus a correction term rather than a direct subtraction of two separately-rounded products. This achieves near full double precision even when the naive `(- (* a b) (* c d))` loses many significant digits to cancellation. Requires a true hardware/JVM fused multiply-add (Java 9+) to realize the accuracy benefit; on earlier JVMs it is numerically equivalent to the naive computation. See also [[sum-of-products]], [[fma]].
(dist [x1 y1] [x2 y2])(dist x1 y1 x2 y2)Computes the Euclidean distance between two 2D points (x1,y1) and (x2,y2).
Parameters:
[x1 y1], [x2 y2] (pairs of doubles): the two points, for the 2-arity form.x1, y1, x2, y2 (doubles): the two points' coordinates directly, for the 4-arity form.Returns the distance as a double.
See also qdist (fast, less accurate version), hypot-sqrt.
Computes the Euclidean distance between two 2D points `(x1,y1)` and `(x2,y2)`. Parameters: - `[x1 y1]`, `[x2 y2]` (pairs of doubles): the two points, for the 2-arity form. - `x1`, `y1`, `x2`, `y2` (doubles): the two points' coordinates directly, for the 4-arity form. Returns the distance as a double. See also [[qdist]] (fast, less accurate version), [[hypot-sqrt]].
Convert double array into sequence.
Alias for seq.
Convert double array into sequence. Alias for `seq`.
The Class object for a primitive double[] array, i.e. (class (double-array 0)).
Used internally (and available for public use) to check whether a value is already a double[] array, e.g. in seq->double-array.
See also double-double-array-type.
The `Class` object for a primitive `double[]` array, i.e. `(class (double-array 0))`. Used internally (and available for public use) to check whether a value is already a `double[]` array, e.g. in [[seq->double-array]]. See also [[double-double-array-type]].
(double-bits v)Returns double as 64-bits (long)
Returns double as 64-bits (long)
(double-double-array->seq res)Converts a double[][] array-of-arrays into a sequence of sequences.
Parameters:
res: a double[][] array (or any seqable collection of seqable rows).Returns a lazy sequence of lazy sequences, one per row, via seq.
See also seq->double-double-array, double-array->seq.
Converts a `double[][]` array-of-arrays into a sequence of sequences. Parameters: - `res`: a `double[][]` array (or any seqable collection of seqable rows). Returns a lazy sequence of lazy sequences, one per row, via `seq`. See also [[seq->double-double-array]], [[double-array->seq]].
The Class object for a primitive double[][] array-of-arrays, i.e. (class (into-array [(double-array 0)])).
Used internally (and available for public use) to check whether a value is already a double[][] array, e.g. in seq->double-double-array.
See also double-array-type.
The `Class` object for a primitive `double[][]` array-of-arrays, i.e. `(class (into-array [(double-array 0)]))`. Used internally (and available for public use) to check whether a value is already a `double[][]` array, e.g. in [[seq->double-double-array]]. See also [[double-array-type]].
(double-exponent v)Extract exponent information from double
Extract exponent information from double
(double-high-bits v)Returns the high 32 bits of v's IEEE 754 bit representation, as an unsigned value held in a long.
Parameters:
v (double): the input value.Returns the top 32 bits of (double-bits v), right-shifted into the low 32 bits of the result. Combine with double-low-bits to reconstruct the full 64-bit pattern (e.g. (bit-or (bit-shift-left (double-high-bits v) 32) (double-low-bits v)) equals (double-bits v)).
See also double-low-bits, double-bits, bits->double.
Returns the high 32 bits of `v`'s IEEE 754 bit representation, as an unsigned value held in a `long`. Parameters: - `v` (double): the input value. Returns the top 32 bits of `(double-bits v)`, right-shifted into the low 32 bits of the result. Combine with [[double-low-bits]] to reconstruct the full 64-bit pattern (e.g. `(bit-or (bit-shift-left (double-high-bits v) 32) (double-low-bits v))` equals `(double-bits v)`). See also [[double-low-bits]], [[double-bits]], [[bits->double]].
(double-low-bits v)Returns the low 32 bits of v's IEEE 754 bit representation, as an unsigned value held in a long.
Parameters:
v (double): the input value.Returns the bottom 32 bits of (double-bits v). See double-high-bits for how to reconstruct the full 64-bit pattern from both halves.
See also double-high-bits, double-bits, bits->double.
Returns the low 32 bits of `v`'s IEEE 754 bit representation, as an unsigned value held in a `long`. Parameters: - `v` (double): the input value. Returns the bottom 32 bits of `(double-bits v)`. See [[double-high-bits]] for how to reconstruct the full 64-bit pattern from both halves. See also [[double-high-bits]], [[double-bits]], [[bits->double]].
Value of 0x1.fffffffffffffp-1d = 0.(9)
Value of 0x1.fffffffffffffp-1d = 0.(9)
(double-significand v)Extracts the 52-bit mantissa (significand) field of v's IEEE 754 bit representation.
Parameters:
v (double): the input value.Returns the low 52 bits of (double-bits v) as a long, i.e. the fractional part of the normalized 1.xxx * 2^e representation, without the implicit leading 1 bit. For a normal, finite v, this is 0 exactly when v is an exact power of two (or zero).
See also double-exponent, double-bits.
Extracts the 52-bit mantissa (significand) field of `v`'s IEEE 754 bit representation. Parameters: - `v` (double): the input value. Returns the low 52 bits of `(double-bits v)` as a `long`, i.e. the fractional part of the normalized `1.xxx * 2^e` representation, without the implicit leading `1` bit. For a normal, finite `v`, this is `0` exactly when `v` is an exact power of two (or zero). See also [[double-exponent]], [[double-bits]].
(eq _)(eq a b)(eq a b & r)Primitive math equality function. Alias for ==.
Parameters:
double values.Returns true if all arguments are equal (chained pairwise: a=b, b=c, c=d, ...), false otherwise, as a Boolean. With one argument returns true.
Primitive math equality function. Alias for [[==]]. Parameters: - one or more `double` values. Returns `true` if all arguments are equal (chained pairwise: `a=b`, `b=c`, `c=d`, ...), `false` otherwise, as a Boolean. With one argument returns `true`. See also [[==]], [[not==]], [[approx-eq]], [[delta-eq]].
(excsc x)Computes the excosecant of x, excsc(x) = csc(x) - 1.
Parameters:
x (double): angle in radians.Returns the excosecant as a double.
Computes the excosecant of `x`, `excsc(x) = csc(x) - 1`. Parameters: - `x` (double): angle in radians. Returns the excosecant as a double. See also [[aexcsc]], [[csc]], [[exsec]].
(expexp x)Computes exp(-exp(-x)), the Gumbel CDF form.
Parameters:
x (double): value.Returns the result as a double, always in [0, 1].
See also cexpexp.
Computes `exp(-exp(-x))`, the Gumbel CDF form. Parameters: - `x` (double): value. Returns the result as a double, always in `[0, 1]`. See also [[cexpexp]].
(expm1 x)exp(x)-1 for small x
Returns x itself for x equal to 0.0 or -0.0, so the sign of a zero is kept.
exp(x)-1 for small x Returns `x` itself for `x` equal to `0.0` or `-0.0`, so the sign of a zero is kept.
(exprel x)Computes (exp(x) - 1) / x, the relative rate of change of exp -- numerically stable near x=0, where the naive formula suffers catastrophic cancellation.
Parameters:
x (double): value to evaluate.Returns the result as a double. Returns exactly 1.0 for |x| below 10 times machine epsilon (the correct limiting value as x -> 0), and ##Inf for x > 717.0 (avoiding exp overflow before it would occur), otherwise computes expm1(x)/x directly.
Computes `(exp(x) - 1) / x`, the relative rate of change of `exp` -- numerically stable near `x=0`, where the naive formula suffers catastrophic cancellation. Parameters: - `x` (double): value to evaluate. Returns the result as a double. Returns exactly `1.0` for `|x|` below `10` times machine epsilon (the correct limiting value as `x -> 0`), and `##Inf` for `x > 717.0` (avoiding `exp` overflow before it would occur), otherwise computes `expm1(x)/x` directly. See also [[expm1]], [[exp]].
(exsec x)Computes the exsecant of x, exsec(x) = sec(x) - 1.
Parameters:
x (double): angle in radians.Returns the exsecant as a double.
Computes the exsecant of `x`, `exsec(x) = sec(x) - 1`. Parameters: - `x` (double): angle in radians. Returns the exsecant as a double. See also [[aexsec]], [[sec]], [[excsc]].
(factorial x)Computes x!, using an exact table lookup for non-negative integers below 21, and the gamma function (exp(logGamma(x+1))) otherwise.
Parameters:
x (double): value to compute the factorial of.Returns the result as a double.
See also factorial20, inv-factorial, log-factorial, falling-factorial, rising-factorial.
Computes `x!`, using an exact table lookup for non-negative integers below `21`, and the gamma function (`exp(logGamma(x+1))`) otherwise. Parameters: - `x` (double): value to compute the factorial of. Returns the result as a double. See also [[factorial20]], [[inv-factorial]], [[log-factorial]], [[falling-factorial]], [[rising-factorial]].
(factorial20 n)Looks up n! from a precomputed table for n in [0, 20].
Parameters:
n (long): index into the factorial table; must be in [0, 20] (20! is the largest factorial exactly representable as a long).Returns n! as a long.
See also factorial.
Looks up `n!` from a precomputed table for `n` in `[0, 20]`. Parameters: - `n` (long): index into the factorial table; must be in `[0, 20]` (`20!` is the largest factorial exactly representable as a `long`). Returns `n!` as a long. See also [[factorial]].
(falling-factorial n x)Calculates the falling (descending) factorial of x to the power n.
Defined as the product x*(x-1)*(x-2)*...*(x-n+1) for a non-negative integer n. When n is not a non-negative integer, the definition is extended using the gamma function.
Parameters:
n (double): Number of descending terms.x (double): Starting value.Returns the falling factorial as a double.
See also rising-factorial, falling-factorial-int, factorial, combinations.
Calculates the falling (descending) factorial of `x` to the power `n`. Defined as the product `x*(x-1)*(x-2)*...*(x-n+1)` for a non-negative integer `n`. When `n` is not a non-negative integer, the definition is extended using the gamma function. Parameters: - `n` (double): Number of descending terms. - `x` (double): Starting value. Returns the falling factorial as a double. See also [[rising-factorial]], [[falling-factorial-int]], [[factorial]], [[combinations]].
(falling-factorial-int n x)Computes the falling (descending) factorial of x to the power of an integer n, x*(x-1)*...*(x-n+1).
Parameters:
n (long): number of descending terms; may be negative, in which case the result is the reciprocal of the falling factorial with n negated and x shifted by n.x (double): starting value.Returns the falling factorial as a double.
See also falling-factorial, rising-factorial-int.
Computes the falling (descending) factorial of `x` to the power of an integer `n`, `x*(x-1)*...*(x-n+1)`. Parameters: - `n` (long): number of descending terms; may be negative, in which case the result is the reciprocal of the falling factorial with `n` negated and `x` shifted by `n`. - `x` (double): starting value. Returns the falling factorial as a double. See also [[falling-factorial]], [[rising-factorial-int]].
(fast*)(fast* a)(fast* a b)(fast* a b & r)Primitive and inlined * as a function
Primitive and inlined `*` as a function
(fast+)(fast+ a)(fast+ a b)(fast+ a b & r)Primitive and inlined + as a function
Primitive and inlined `+` as a function
(fast-)(fast- a)(fast- a b)(fast- a b & r)Primitive and inlined - as a function
Primitive and inlined `-` as a function
(fast-div)(fast-div a)(fast-div a b)(fast-div a b & r)Primitive and inlined / as a function
Primitive and inlined `/` as a function
(fast-max a)(fast-max a b)(fast-max a b & r)Primitive and inlined max as a function
Primitive and inlined `max` as a function
(fast-min a)(fast-min a b)(fast-min a b & r)Primitive and inlined min as a function
Primitive and inlined `min` as a function
(fatan2 x y)Computes atan2 with Jafama FastMath, which is faster than atan2 but less accurate.
The error is larger than that of atan2. Use atan2 when accuracy matters.
Parameters:
x (double): the first argument, as in atan2 (the ordinate of the point, the y of Math.atan2).y (double): the second argument, as in atan2 (the abscissa of the point, the x of Math.atan2).Returns the angle in radians in the range [-π, π] as a double.
See also atan2.
Computes `atan2` with Jafama `FastMath`, which is faster than [[atan2]] but less accurate. The error is larger than that of [[atan2]]. Use [[atan2]] when accuracy matters. Parameters: - `x` (double): the first argument, as in [[atan2]] (the ordinate of the point, the `y` of `Math.atan2`). - `y` (double): the second argument, as in [[atan2]] (the abscissa of the point, the `x` of `Math.atan2`). Returns the angle in radians in the range `[-π, π]` as a double. See also [[atan2]].
(fcos x)Computes cos(x) with Jafama FastMath, which is faster than cos but less accurate.
The error is small in absolute terms but can be large in relative terms, in particular next to the zeros of the cosine (odd multiples of π/2). Use cos when relative accuracy matters.
Parameters:
x (double): angle in radians.Returns cos(x) as a double. Returns ##NaN when x is infinite or ##NaN.
Computes `cos(x)` with Jafama `FastMath`, which is faster than [[cos]] but less accurate. The error is small in absolute terms but can be large in relative terms, in particular next to the zeros of the cosine (odd multiples of `π/2`). Use [[cos]] when relative accuracy matters. Parameters: - `x` (double): angle in radians. Returns `cos(x)` as a double. Returns `##NaN` when `x` is infinite or `##NaN`. See also [[cos]], [[qcos]].
(flog1p x)Computes log(1+x) with Jafama FastMath, which is faster than log1p but less accurate.
The error is larger than that of log1p. Use log1p when accuracy matters.
Parameters:
x (double): value to evaluate, x >= -1.Returns log(1+x) as a double. Returns ##NaN for x < -1 and ##-Inf for x = -1.
Computes `log(1+x)` with Jafama `FastMath`, which is faster than [[log1p]] but less accurate. The error is larger than that of [[log1p]]. Use [[log1p]] when accuracy matters. Parameters: - `x` (double): value to evaluate, `x >= -1`. Returns `log(1+x)` as a double. Returns `##NaN` for `x < -1` and `##-Inf` for `x = -1`. See also [[log1p]], [[log]].
(floor x)(floor x scale)Rounds x towards negative infinity.
Parameters:
x (double): the number to round.scale (double, optional): if given, x is divided by scale, floored, then multiplied back by scale -- i.e. rounds to the nearest multiple of scale towards negative infinity.Returns the rounded value as a double.
Rounds `x` towards negative infinity. Parameters: - `x` (double): the number to round. - `scale` (double, optional): if given, `x` is divided by `scale`, floored, then multiplied back by `scale` -- i.e. rounds to the nearest multiple of `scale` towards negative infinity. Returns the rounded value as a double. See also [[ceil]], [[round]], [[qfloor]].
(fma x y z)Computes x*y + z using fused multiply-add when available. Identical implementation to muladd.
Parameters:
x, y, z (doubles): multiplicands and addend.Returns x*y + z as a double. On Java 9+, uses Math/fma for a single correctly-rounded fused multiply-add (more accurate than a separate multiply and add). On earlier JVMs, falls back to a plain (+ z (* x y)) with intermediate rounding.
See also muladd, negmuladd, difference-of-products, sum-of-products.
Computes `x*y + z` using fused multiply-add when available. Identical implementation to [[muladd]]. Parameters: - `x`, `y`, `z` (doubles): multiplicands and addend. Returns `x*y + z` as a double. On Java 9+, uses `Math/fma` for a single correctly-rounded fused multiply-add (more accurate than a separate multiply and add). On earlier JVMs, falls back to a plain `(+ z (* x y))` with intermediate rounding. See also [[muladd]], [[negmuladd]], [[difference-of-products]], [[sum-of-products]].
(fpow x exponent)Fast version of pow where exponent is integer.
Fast version of pow where exponent is integer.
(frac v)Unsigned fractional part of v.
Parameters:
v (double): the input value.Returns (abs (- v (trunc v))), i.e. the magnitude of the part of v remaining after truncation towards zero. Always in the range [0.0, 1.0), 0.0 for every v beyond 2^52 in magnitude (all such doubles are integers). NaN for infinite and NaN input.
See also sfrac for the signed version.
Unsigned fractional part of `v`. Parameters: - `v` (double): the input value. Returns `(abs (- v (trunc v)))`, i.e. the magnitude of the part of `v` remaining after truncation towards zero. Always in the range `[0.0, 1.0)`, `0.0` for every `v` beyond `2^52` in magnitude (all such doubles are integers). `NaN` for infinite and `NaN` input. See also [[sfrac]] for the signed version.
(fsin x)Computes sin(x) with Jafama FastMath, which is faster than sin but less accurate.
The error is small in absolute terms but can be large in relative terms, in particular for small x and next to the zeros of the sine (multiples of π). Use sin when relative accuracy matters.
Parameters:
x (double): angle in radians.Returns sin(x) as a double. Returns ##NaN when x is infinite or ##NaN.
Computes `sin(x)` with Jafama `FastMath`, which is faster than [[sin]] but less accurate. The error is small in absolute terms but can be large in relative terms, in particular for small `x` and next to the zeros of the sine (multiples of `π`). Use [[sin]] when relative accuracy matters. Parameters: - `x` (double): angle in radians. Returns `sin(x)` as a double. Returns `##NaN` when `x` is infinite or `##NaN`. See also [[sin]], [[qsin]].
(ftan x)Computes tan(x) with Jafama FastMath, which is faster than tan but less accurate.
The error is small in absolute terms but can be very large in relative terms, in particular next to the zeros of the tangent (multiples of π) and next to its poles (odd multiples of π/2). Use tan when relative accuracy matters.
Parameters:
x (double): angle in radians.Returns tan(x) as a double. Returns ##NaN when x is infinite or ##NaN.
See also tan.
Computes `tan(x)` with Jafama `FastMath`, which is faster than [[tan]] but less accurate. The error is small in absolute terms but can be very large in relative terms, in particular next to the zeros of the tangent (multiples of `π`) and next to its poles (odd multiples of `π/2`). Use [[tan]] when relative accuracy matters. Parameters: - `x` (double): angle in radians. Returns `tan(x)` as a double. Returns `##NaN` when `x` is infinite or `##NaN`. See also [[tan]].
(gcd a b)Calculates the greatest common divisor of two integers, using Stein's binary GCD algorithm.
Parameters:
a, b (longs): the two integers. May be negative; sign is ignored.Returns the largest non-negative n that divides both (abs a) and (abs b), as a long. Returns (abs a) when b is 0, (abs b) when a is 0, and 0 when both are 0.
See also lcm.
Calculates the greatest common divisor of two integers, using Stein's binary GCD algorithm. Parameters: - `a`, `b` (longs): the two integers. May be negative; sign is ignored. Returns the largest non-negative `n` that divides both `(abs a)` and `(abs b)`, as a `long`. Returns `(abs a)` when `b` is `0`, `(abs b)` when `a` is `0`, and `0` when both are `0`. See also [[lcm]].
(group-by-intervals coll)(group-by-intervals intervals coll)Groups values from a sequence coll into specified intervals.
The function partitions the values in coll based on which interval they fall into.
Each interval is a 2-element vector [lower upper]. Values are included in an interval if they are strictly greater than the lower bound and less than or equal to the upper bound, using between-?.
Arguments:
intervals: A sequence of 2-element vectors representing the intervals [lower upper].coll: A collection of numerical values to be grouped.If intervals are not provided, the function first calculates overlapping intervals using co-intervals from the values in coll, and then groups the values into these generated intervals.
Returns a map where keys are the interval vectors and values are sequences of the numbers from coll that fall within that interval.
Groups values from a sequence `coll` into specified intervals. The function partitions the values in `coll` based on which interval they fall into. Each interval is a 2-element vector `[lower upper]`. Values are included in an interval if they are strictly greater than the `lower` bound and less than or equal to the `upper` bound, using [[between-?]]. Arguments: - `intervals`: A sequence of 2-element vectors representing the intervals `[lower upper]`. - `coll`: A collection of numerical values to be grouped. If `intervals` are not provided, the function first calculates overlapping intervals using [[co-intervals]] from the values in `coll`, and then groups the values into these generated intervals. Returns a map where keys are the interval vectors and values are sequences of the numbers from `coll` that fall within that interval.
(hacovercos x)Computes the hacovercosine of x, hacovercos(x) = (1 + sin(x))/2.
Parameters:
x (double): angle in radians.Returns the hacovercosine as a double, always in [0, 1].
See also ahacovercos, covercos, haversin.
Computes the hacovercosine of `x`, `hacovercos(x) = (1 + sin(x))/2`. Parameters: - `x` (double): angle in radians. Returns the hacovercosine as a double, always in `[0, 1]`. See also [[ahacovercos]], [[covercos]], [[haversin]].
(hacoversin x)Computes the hacoversine of x, hacoversin(x) = (1 - sin(x))/2.
Parameters:
x (double): angle in radians.Returns the hacoversine as a double, always in [0, 1].
See also ahacoversin, coversin, haversin.
Computes the hacoversine of `x`, `hacoversin(x) = (1 - sin(x))/2`. Parameters: - `x` (double): angle in radians. Returns the hacoversine as a double, always in `[0, 1]`. See also [[ahacoversin]], [[coversin]], [[haversin]].
(havercos x)Computes the havercosine of x, havercos(x) = (1 + cos(x))/2.
Parameters:
x (double): angle in radians.Returns the havercosine as a double, always in [0, 1].
Computes the havercosine of `x`, `havercos(x) = (1 + cos(x))/2`. Parameters: - `x` (double): angle in radians. Returns the havercosine as a double, always in `[0, 1]`. See also [[ahavercos]], [[vercos]], [[haversin]].
(haversin x)(haversin [lat1 lon1] [lat2 lon2])(haversin lat1 lon1 lat2 lon2)Computes the haversine of x, haversin(x) = (1 - cos(x))/2, or the haversine-formula central angle between two latitude/longitude points (in radians).
Parameters:
x (double): angle in radians, for the 1-arity form.[lat1 lon1], [lat2 lon2] (pairs of doubles): coordinates in radians, for the 2-arity form.lat1, lon1, lat2, lon2 (doubles): coordinates in radians, for the 4-arity form.Returns the haversine value as a double, always in [0, 1]. For the 2- and 4-arity forms, returns the haversine of the central angle between the two points, via hav(dlat) + cos(lat1)*cos(lat2)*hav(dlon).
See also haversine (alias), haversine-dist, versin.
Computes the haversine of `x`, `haversin(x) = (1 - cos(x))/2`, or the haversine-formula central angle between two latitude/longitude points (in radians). Parameters: - `x` (double): angle in radians, for the 1-arity form. - `[lat1 lon1]`, `[lat2 lon2]` (pairs of doubles): coordinates in radians, for the 2-arity form. - `lat1`, `lon1`, `lat2`, `lon2` (doubles): coordinates in radians, for the 4-arity form. Returns the haversine value as a double, always in `[0, 1]`. For the 2- and 4-arity forms, returns the haversine of the central angle between the two points, via `hav(dlat) + cos(lat1)*cos(lat2)*hav(dlon)`. See also [[haversine]] (alias), [[haversine-dist]], [[versin]].
(haversine-dist [lat1 lon1] [lat2 lon2])(haversine-dist lat1 lon1 lat2 lon2)Computes the great-circle distance between two latitude/longitude points on a unit sphere (r=1), using the haversine formula.
Parameters:
[lat1 lon1], [lat2 lon2] (pairs of doubles): coordinates in radians, for the 2-arity form.lat1, lon1, lat2, lon2 (doubles): coordinates in radians, for the 4-arity form.Returns the great-circle distance in radians as a double (the central angle between the two points). Multiply by a sphere's radius to get the distance in that radius's units (e.g. multiply by Earth's mean radius, ~6371 km, for a distance in kilometers).
See also haversin.
Computes the great-circle distance between two latitude/longitude points on a unit sphere (`r=1`), using the haversine formula. Parameters: - `[lat1 lon1]`, `[lat2 lon2]` (pairs of doubles): coordinates in radians, for the 2-arity form. - `lat1`, `lon1`, `lat2`, `lon2` (doubles): coordinates in radians, for the 4-arity form. Returns the great-circle distance in radians as a double (the central angle between the two points). Multiply by a sphere's radius to get the distance in that radius's units (e.g. multiply by Earth's mean radius, ~6371 km, for a distance in kilometers). See also [[haversin]].
(high-2-exp x)Finds the smallest integer n such that 2^n is not smaller than the absolute value of x.
Equivalent to the ceiling of the base-2 logarithm of |x|. Together with low-2-exp it brackets |x| between two consecutive powers of two.
Computed bit-exactly (via low-2-exp plus a check of whether |x|'s mantissa is exactly zero, i.e. whether |x| is itself an exact power of two), not via a floating-point logarithm, so it is exact for every finite, normal double.
Parameters:
x (double): Input value.Returns the exponent n as a long. Returns -1023 for x equal to 0.0 or subnormal (matches low-2-exp's convention for the same inputs).
Finds the smallest integer `n` such that `2^n` is not smaller than the absolute value of `x`. Equivalent to the ceiling of the base-2 logarithm of `|x|`. Together with [[low-2-exp]] it brackets `|x|` between two consecutive powers of two. Computed bit-exactly (via [[low-2-exp]] plus a check of whether `|x|`'s mantissa is exactly zero, i.e. whether `|x|` is itself an exact power of two), not via a floating-point logarithm, so it is exact for every finite, normal double. Parameters: - `x` (double): Input value. Returns the exponent `n` as a long. Returns `-1023` for `x` equal to `0.0` or subnormal (matches [[low-2-exp]]'s convention for the same inputs). See also [[low-2-exp]], [[high-exp]].
(high-exp b x)Finds the smallest integer n such that b^n is not smaller than the absolute value of x.
Equivalent to the ceiling of the base-b logarithm of |x|. Together with low-exp it brackets |x| between two consecutive powers of b.
Parameters:
b (double): Base, must be positive and not equal to 1.0.x (double): Input value.Returns the exponent n as a long.
Computed by rounding the (floating-point, therefore imprecise) base-b logarithm to the nearest integer, then verifying that candidate against b^n directly and correcting by one if needed -- this avoids the systematic off-by-one a plain ceil(logb x) has at an exact power of b (there is no bit-exact shortcut for an arbitrary base, unlike high-2-exp for base 2).
See also low-exp, high-2-exp.
Finds the smallest integer `n` such that `b^n` is not smaller than the absolute value of `x`. Equivalent to the ceiling of the base-`b` logarithm of `|x|`. Together with [[low-exp]] it brackets `|x|` between two consecutive powers of `b`. Parameters: - `b` (double): Base, must be positive and not equal to `1.0`. - `x` (double): Input value. Returns the exponent `n` as a long. Computed by rounding the (floating-point, therefore imprecise) base-`b` logarithm to the nearest integer, then verifying that candidate against `b^n` directly and correcting by one if needed -- this avoids the systematic off-by-one a plain `ceil(logb x)` has at an exact power of `b` (there is no bit-exact shortcut for an arbitrary base, unlike [[high-2-exp]] for base 2). See also [[low-exp]], [[high-2-exp]].
(hypot x y)(hypot x y z)Calculates the Euclidean norm (distance from the origin) for 2 or 3 arguments.
It uses a numerically stable algorithm to avoid intermediate overflow or underflow.
See also hypot-sqrt for the direct calculation.
Calculates the Euclidean norm (distance from the origin) for 2 or 3 arguments. It uses a numerically stable algorithm to avoid intermediate overflow or underflow. See also [[hypot-sqrt]] for the direct calculation.
(hypot-sqrt x y)(hypot-sqrt x y z)Calculates the Euclidean norm (distance from the origin) using a direct sqrt of sum of squares.
Note: This method can be less numerically stable than hypot for inputs with vastly different magnitudes.
Calculates the Euclidean norm (distance from the origin) using a direct sqrt of sum of squares. Note: This method can be less numerically stable than [[hypot]] for inputs with vastly different magnitudes.
(iabs x)Absolute value, long version. See abs.
Absolute value, `long` version. See [[abs]].
(inc x)Primitive and inlined inc. A direct call with an integer argument can return a long via :inline; called indirectly (apply, higher-order use), always returns a double (same value, see +).
Primitive and inlined `inc`. A direct call with an integer argument can return a `long` via `:inline`; called indirectly (`apply`, higher-order use), always returns a `double` (same value, see [[+]]).
(inf? v)Check if a number is an infinite (positive or negative).
Check if a number is an infinite (positive or negative).
(integer? v)Checks if a given real number is a mathematical integer (has zero fractional part).
Parameters:
v (double): value to check.Returns true when v equals its own rounded value (v == rint(v)), false otherwise. Shadows clojure.core/integer?, which instead checks the value's Java type; this predicate checks the numeric value, so (integer? 5.0) returns true.
Checks if a given real number is a mathematical integer (has zero fractional part). Parameters: - `v` (double): value to check. Returns `true` when `v` equals its own rounded value (`v == rint(v)`), `false` otherwise. Shadows `clojure.core/integer?`, which instead checks the value's Java type; this predicate checks the numeric value, so `(integer? 5.0)` returns `true`. See also [[frac]], [[sfrac]].
(inv-factorial x)Computes 1/x!, the reciprocal of factorial.
Parameters:
x (double): value to compute the inverse factorial of.Returns the result as a double.
See also factorial.
Computes `1/x!`, the reciprocal of [[factorial]]. Parameters: - `x` (double): value to compute the inverse factorial of. Returns the result as a double. See also [[factorial]].
Value of $\frac{1}{\ln{\frac{1}{2}}}$
Value of $\frac{1}{\ln{\frac{1}{2}}}$
(invalid-double? v)Check if a number is not finite double (NaN or ±Inf).
Check if a number is not finite double (NaN or ±Inf).
(itrunc v)Truncates the fractional part of v, rounding towards zero.
Parameters:
v (double): the number to truncate.Returns the integer part of v as a long, preserving sign: qceil for negative v, qfloor otherwise.
See also trunc.
Truncates the fractional part of `v`, rounding towards zero. Parameters: - `v` (double): the number to truncate. Returns the integer part of `v` as a `long`, preserving sign: [[qceil]] for negative `v`, [[qfloor]] otherwise. See also [[trunc]].
(lcm a b)Calculates the least common multiple of two integers, using Stein's binary GCD algorithm internally.
Parameters:
a, b (longs): the two integers. May be negative; sign is ignored.Returns the smallest non-negative n such that n is a multiple of both (abs a) and (abs b), as a long. Returns 0 if either argument is 0.
See also gcd.
Calculates the least common multiple of two integers, using Stein's binary GCD algorithm internally. Parameters: - `a`, `b` (longs): the two integers. May be negative; sign is ignored. Returns the smallest non-negative `n` such that `n` is a multiple of both `(abs a)` and `(abs b)`, as a `long`. Returns `0` if either argument is `0`. See also [[gcd]].
(least-significant-bit v)Returns the least significant bit position.
Returns -1 for 0
Returns the least significant bit position. Returns `-1` for `0`
(lerp start stop t)Linearly interpolates between start and stop by amount t.
Parameters:
start, stop (doubles): the two endpoints.t (double): interpolation amount, typically in [0,1].Returns start when t=0, stop when t=1, and extrapolates linearly outside [0,1].
See also mlerp (macro version), cos-interpolation, quad-interpolation, smooth-interpolation (other, non-linear easing curves).
Linearly interpolates between `start` and `stop` by amount `t`. Parameters: - `start`, `stop` (doubles): the two endpoints. - `t` (double): interpolation amount, typically in `[0,1]`. Returns `start` when `t=0`, `stop` when `t=1`, and extrapolates linearly outside `[0,1]`. See also [[mlerp]] (macro version), [[cos-interpolation]], [[quad-interpolation]], [[smooth-interpolation]] (other, non-linear easing curves).
(log x)(log base x)Computes the natural logarithm of x, or the logarithm of x with a given base.
Parameters:
x (double): value to take the logarithm of; must be positive for a real result.base, x (doubles), 2-arity: computes log(x)/log(base) (change of base).Returns the logarithm as a double. Returns ##NaN for x < 0, and ##-Inf for x = 0, matching Math/log's IEEE 754 behavior.
See also ln (alias, 1-arity only), log10, log2, logb, log1p.
Computes the natural logarithm of `x`, or the logarithm of `x` with a given `base`. Parameters: - `x` (double): value to take the logarithm of; must be positive for a real result. - `base`, `x` (doubles), 2-arity: computes `log(x)/log(base)` (change of base). Returns the logarithm as a double. Returns `##NaN` for `x < 0`, and `##-Inf` for `x = 0`, matching `Math/log`'s IEEE 754 behavior. See also [[ln]] (alias, 1-arity only), [[log10]], [[log2]], [[logb]], [[log1p]].
(log-combinations n k)Computes the logarithm of the binomial coefficient, log(n choose k).
Parameters:
n (long): total number of items.k (long): number of items to choose.Returns the result as a double, ##-Inf when k is negative or greater than n, 0.0 when k is 0 or k equals n.
See also combinations, log-factorial.
Computes the logarithm of the binomial coefficient, `log(n choose k)`. Parameters: - `n` (long): total number of items. - `k` (long): number of items to choose. Returns the result as a double, `##-Inf` when `k` is negative or greater than `n`, `0.0` when `k` is `0` or `k` equals `n`. See also [[combinations]], [[log-factorial]].
(log-factorial x)Computes log(x!), equivalent to log-gamma(x+1).
Parameters:
x (double): value to compute the log-factorial of.Returns the result as a double.
See also factorial, log-stirling-factorial, log-combinations.
Computes `log(x!)`, equivalent to `log-gamma(x+1)`. Parameters: - `x` (double): value to compute the log-factorial of. Returns the result as a double. See also [[factorial]], [[log-stirling-factorial]], [[log-combinations]].
(log-stirling-factorial x)Approximates log(x!) using Stirling's asymptotic series with a 6-term correction, without relying on the gamma function.
Parameters:
x (double): value to approximate the log-factorial of; accuracy improves for larger x.Returns the approximate result as a double.
See also log-factorial, stirling-factorial.
Approximates `log(x!)` using Stirling's asymptotic series with a 6-term correction, without relying on the gamma function. Parameters: - `x` (double): value to approximate the log-factorial of; accuracy improves for larger `x`. Returns the approximate result as a double. See also [[log-factorial]], [[stirling-factorial]].
(log1mexp x)Computes log(1-exp(x)) for x < 0, using a numerically stable form to avoid catastrophic cancellation near x=0.
Parameters:
x (double): value to evaluate; must be negative.Returns the result as a double, always non-positive.
Computes `log(1-exp(x))` for `x < 0`, using a numerically stable form to avoid catastrophic cancellation near `x=0`. Parameters: - `x` (double): value to evaluate; must be negative. Returns the result as a double, always non-positive. See also [[log1pexp]], [[log2mexp]].
(log1p x)log(1+x) for small x
See also flog1p.
log(1+x) for small x See also [[flog1p]].
(log1pexp x)Computes log(1+exp(x)) (the softplus function), using a numerically stable piecewise approximation to avoid overflow for large x and underflow for very negative x.
Parameters:
x (double): value to evaluate.Returns the result as a double. Returns 0.0 for very negative x, and x itself for very large x (where exp(x) would overflow but the correction term becomes negligible), with a stable computation in between.
Computes `log(1+exp(x))` (the softplus function), using a numerically stable piecewise approximation to avoid overflow for large `x` and underflow for very negative `x`. Parameters: - `x` (double): value to evaluate. Returns the result as a double. Returns `0.0` for very negative `x`, and `x` itself for very large `x` (where `exp(x)` would overflow but the correction term becomes negligible), with a stable computation in between. See also [[log1mexp]], [[logaddexp]], [[expm1]].
(log1pmx x)Computes log(1+x) - x, using a stable kernel-based polynomial approximation near x=0 to avoid catastrophic cancellation (ported from Julia's Base.Math).
Parameters:
x (double): value to evaluate; must satisfy x > -1 for a real result.Returns the result as a double, always non-positive.
Computes `log(1+x) - x`, using a stable kernel-based polynomial approximation near `x=0` to avoid catastrophic cancellation (ported from Julia's `Base.Math`). Parameters: - `x` (double): value to evaluate; must satisfy `x > -1` for a real result. Returns the result as a double, always non-positive. See also [[logmxp1]], [[log1p]].
(log1psq x)Computes log(1+x^2), switching to a direct formula for very large x to avoid unnecessary precision loss in x*x.
Parameters:
x (double): value to evaluate.Returns the result as a double, always non-negative.
See also log1p.
Computes `log(1+x^2)`, switching to a direct formula for very large `x` to avoid unnecessary precision loss in `x*x`. Parameters: - `x` (double): value to evaluate. Returns the result as a double, always non-negative. See also [[log1p]].
(log2 x)Computes the base-2 logarithm of x.
Parameters:
x (double): value to take the logarithm of; must be positive for a real result.Returns the result as a double, within about half an ulp of the exact value (a port of the FreeBSD/fdlibm log2); exact for every power of two. Returns ##-Inf for 0.0 and -0.0, ##Inf for ##Inf, and ##NaN for negative x and ##NaN.
Computes the base-2 logarithm of `x`. Parameters: - `x` (double): value to take the logarithm of; must be positive for a real result. Returns the result as a double, within about half an ulp of the exact value (a port of the FreeBSD/fdlibm `log2`); exact for every power of two. Returns `##-Inf` for `0.0` and `-0.0`, `##Inf` for `##Inf`, and `##NaN` for negative `x` and `##NaN`. See also [[log]], [[logb]], [[LOG2E]].
(log2int v)Fast, exact computation of log2(v) rounded to the nearest integer, using only bit-level exponent/significand extraction (no floating-point logarithm, so no log-based rounding error).
Parameters:
v (double): input value, must be positive and finite. Behavior for v<=0.0, NaN, or infinite v is undefined (bit-level artifacts of the underlying exponent extraction, not a meaningful log2 value).Returns round(log2(v)) as a long: the closest integer power-of-two exponent to v, with exact ties (v exactly halfway between two powers of two, e.g. 2^1.5) rounding down to the lower exponent.
See also log2, low-2-exp, high-2-exp.
Fast, exact computation of `log2(v)` rounded to the nearest integer, using only bit-level exponent/significand extraction (no floating-point logarithm, so no log-based rounding error). Parameters: - `v` (double): input value, must be positive and finite. Behavior for `v<=0.0`, `NaN`, or infinite `v` is undefined (bit-level artifacts of the underlying exponent extraction, not a meaningful log2 value). Returns `round(log2(v))` as a `long`: the closest integer power-of-two exponent to `v`, with exact ties (`v` exactly halfway between two powers of two, e.g. `2^1.5`) rounding down to the lower exponent. See also [[log2]], [[low-2-exp]], [[high-2-exp]].
(log2mexp x)Computes log(2-exp(x)), equivalent to log1p(-expm1(x)).
Parameters:
x (double): value to evaluate.Returns the result as a double.
Computes `log(2-exp(x))`, equivalent to `log1p(-expm1(x))`. Parameters: - `x` (double): value to evaluate. Returns the result as a double. See also [[log1mexp]], [[expm1]].
(logaddexp x y)Computes log(exp(x)+exp(y)), the numerically stable 2-argument log-sum-exp.
Parameters:
x, y (doubles): values to combine.Returns the result as a double, computed without overflowing exp(x)/exp(y) for large arguments. Equal infinite arguments return that infinity.
Computes `log(exp(x)+exp(y))`, the numerically stable 2-argument log-sum-exp. Parameters: - `x`, `y` (doubles): values to combine. Returns the result as a double, computed without overflowing `exp(x)`/`exp(y)` for large arguments. Equal infinite arguments return that infinity. See also [[logsumexp]] (n-ary version), [[logsubexp]], [[log1pexp]].
(logb b x)Computes the logarithm of x with an explicit base b, logb(b,x) = log(x)/log(b).
Parameters:
b (double): logarithm base; must be positive and not equal to 1.0.x (double): value to take the logarithm of; must be positive for a real result.Returns the result as a double.
Computes the logarithm of `x` with an explicit base `b`, `logb(b,x) = log(x)/log(b)`. Parameters: - `b` (double): logarithm base; must be positive and not equal to `1.0`. - `x` (double): value to take the logarithm of; must be positive for a real result. Returns the result as a double. See also [[log]] (2-arity form), [[log2]].
(logcosh x)Computes log(cosh(x)), using a numerically stable form (|x| + log1pexp(-2|x|) - ln(2)) to avoid overflow in cosh(x) for large |x|.
Parameters:
x (double): value to evaluate.Returns the result as a double, always non-negative.
Computes `log(cosh(x))`, using a numerically stable form (`|x| + log1pexp(-2|x|) - ln(2)`) to avoid overflow in `cosh(x)` for large `|x|`. Parameters: - `x` (double): value to evaluate. Returns the result as a double, always non-negative. See also [[cosh]], [[log1pexp]].
(logexpm1 x)Computes log(exp(x)-1), the inverse of log1pexp (softplus).
Parameters:
x (double): value to evaluate; must be positive for a real result (exp(x)-1 must be positive).Returns the result as a double. Returns ##NaN for x < 0 and ##NaN, ##-Inf for 0.0, and x itself for x >= 36.8, where log(exp(x)-1) rounds to x (no overflow for large x).
Computes `log(exp(x)-1)`, the inverse of [[log1pexp]] (softplus). Parameters: - `x` (double): value to evaluate; must be positive for a real result (`exp(x)-1` must be positive). Returns the result as a double. Returns `##NaN` for `x < 0` and `##NaN`, `##-Inf` for `0.0`, and `x` itself for `x >= 36.8`, where `log(exp(x)-1)` rounds to `x` (no overflow for large `x`). See also [[log1pexp]], [[expm1]].
(logit x)Computes the logit function (log-odds), logit(x) = log(x/(1-x)), the inverse of sigmoid. Uses a numerically stable, log1p-based reformulation near x=0.5 to avoid catastrophic cancellation.
Parameters:
x (double): probability-like value; must satisfy 0 < x < 1 for a finite result.Returns the result as a double.
See also sigmoid (inverse).
Computes the logit function (log-odds), `logit(x) = log(x/(1-x))`, the inverse of [[sigmoid]]. Uses a numerically stable, `log1p`-based reformulation near `x=0.5` to avoid catastrophic cancellation. Parameters: - `x` (double): probability-like value; must satisfy `0 < x < 1` for a finite result. Returns the result as a double. See also [[sigmoid]] (inverse).
(loglog x)Computes the log-log function, loglog(x) = -log(-log(x)), used as a link function for binary/count models.
Parameters:
x (double): probability-like value; must satisfy 0 < x < 1 for a real result.Returns the result as a double.
See also cloglog.
Computes the log-log function, `loglog(x) = -log(-log(x))`, used as a link function for binary/count models. Parameters: - `x` (double): probability-like value; must satisfy `0 < x < 1` for a real result. Returns the result as a double. See also [[cloglog]].
(logmxp1 x)Computes log(x) - x + 1, using a stable formulation for x near 1 (reusing log1pmx's kernel).
Parameters:
x (double): value to evaluate; must be positive for a real result.Returns the result as a double, always non-positive.
See also log1pmx.
Computes `log(x) - x + 1`, using a stable formulation for `x` near `1` (reusing [[log1pmx]]'s kernel). Parameters: - `x` (double): value to evaluate; must be positive for a real result. Returns the result as a double, always non-positive. See also [[log1pmx]].
(logsubexp x y)Computes log(abs(exp(x)-exp(y))), the numerically stable log-difference-of-exponentials.
Parameters:
x, y (doubles): values to combine.Returns the result as a double. Returns ##-Inf when x equals y (since the difference is zero).
Computes `log(abs(exp(x)-exp(y)))`, the numerically stable log-difference-of-exponentials. Parameters: - `x`, `y` (doubles): values to combine. Returns the result as a double. Returns `##-Inf` when `x` equals `y` (since the difference is zero). See also [[logaddexp]], [[log1mexp]].
(logsumexp xs)Computes log(exp(x1)+...+exp(xn)), the numerically stable n-ary log-sum-exp, using an online (single-pass) running-maximum algorithm.
Parameters:
xs (sequence of doubles): values to combine.Returns the result as a double, computed without overflowing any individual exp(xi) for large arguments. Infinite elements give the limits (##-Inf elements contribute nothing, any ##Inf gives ##Inf), an empty sequence gives ##-Inf, a single element is returned as is (the sign of zero kept), and any ##NaN gives ##NaN.
See also logaddexp (2-arity version).
Computes `log(exp(x1)+...+exp(xn))`, the numerically stable n-ary log-sum-exp, using an online (single-pass) running-maximum algorithm. Parameters: - `xs` (sequence of doubles): values to combine. Returns the result as a double, computed without overflowing any individual `exp(xi)` for large arguments. Infinite elements give the limits (`##-Inf` elements contribute nothing, any `##Inf` gives `##Inf`), an empty sequence gives `##-Inf`, a single element is returned as is (the sign of zero kept), and any `##NaN` gives `##NaN`. See also [[logaddexp]] (2-arity version).
(long-abs x)Absolute value of a long, computed with a branch-free bitwise trick.
Parameters:
x (long): the input value.Returns x if non-negative, -x otherwise, as a long. For x equal to Long/MIN_VALUE, returns x unchanged (its true absolute value overflows the long range), matching Math/abs's behavior for long.
See also abs.
Absolute value of a `long`, computed with a branch-free bitwise trick. Parameters: - `x` (long): the input value. Returns `x` if non-negative, `-x` otherwise, as a `long`. For `x` equal to `Long/MIN_VALUE`, returns `x` unchanged (its true absolute value overflows the `long` range), matching `Math/abs`'s behavior for `long`. See also [[abs]].
(long-add)(long-add a)(long-add a b)(long-add a b c)(long-add a b c d)(long-add a b c d & r)Adds numbers together, coercing arguments and the result to long. Primitive and inlined replacement for clojure.core/+.
Parameters:
long.Returns the sum as a long, following standard JVM two's complement overflow wraparound (no overflow checking). With no arguments returns 0. With one argument returns it unchanged.
Adds numbers together, coercing arguments and the result to `long`. Primitive and inlined replacement for `clojure.core/+`. Parameters: - zero or more values coercible to `long`. Returns the sum as a long, following standard JVM two's complement overflow wraparound (no overflow checking). With no arguments returns `0`. With one argument returns it unchanged. See also [[+]] (double version), [[long-sub]], [[long-mult]], [[long-div]].
(long-dec x)Primitive and inlined dec coerced to a long
Primitive and inlined `dec` coerced to a long
(long-div a)(long-div a b)(long-div a b c)(long-div a b c d)(long-div a b c d & r)Divides numbers, or returns the reciprocal of a single value, coercing arguments to long. Primitive and inlined replacement for clojure.core//.
Parameters:
long.Returns the reciprocal of the sole argument as a double when called with one value (a long's reciprocal is generally not representable as a long, so this arity does not coerce its result). With two or more arguments, returns the left-to-right cumulative integer division of all arguments as a long. Throws an arithmetic exception on division by zero when two or more arguments are given.
Divides numbers, or returns the reciprocal of a single value, coercing arguments to `long`. Primitive and inlined replacement for `clojure.core//`. Parameters: - one or more values coercible to `long`. Returns the reciprocal of the sole argument as a double when called with one value (a long's reciprocal is generally not representable as a long, so this arity does not coerce its result). With two or more arguments, returns the left-to-right cumulative integer division of all arguments as a long. Throws an arithmetic exception on division by zero when two or more arguments are given. See also [[/]] (double version), [[long-add]], [[long-sub]], [[long-mult]].
(long-inc x)Primitive and inlined inc coerced to a long
Primitive and inlined `inc` coerced to a long
(long-max a)(long-max a b)(long-max a b c)(long-max a b c d)(long-max a b c d & r)Returns the largest of one or more values, coercing arguments and the result to long. Primitive and inlined replacement for clojure.core/max.
Parameters:
long.Returns the maximum value as a long.
Returns the largest of one or more values, coercing arguments and the result to `long`. Primitive and inlined replacement for `clojure.core/max`. Parameters: - one or more values coercible to `long`. Returns the maximum value as a long. See also [[max]] (double version), [[long-min]].
(long-min a)(long-min a b)(long-min a b c)(long-min a b c d)(long-min a b c d & r)Returns the smallest of one or more values, coercing arguments and the result to long. Primitive and inlined replacement for clojure.core/min.
Parameters:
long.Returns the minimum value as a long.
Returns the smallest of one or more values, coercing arguments and the result to `long`. Primitive and inlined replacement for `clojure.core/min`. Parameters: - one or more values coercible to `long`. Returns the minimum value as a long. See also [[min]] (double version), [[long-max]].
(long-mod x y)Primitive and inlined mod coerced to longs
Primitive and inlined `mod` coerced to longs
(long-mult)(long-mult a)(long-mult a b)(long-mult a b c)(long-mult a b c d)(long-mult a b c d & r)Multiplies numbers together, coercing arguments and the result to long. Primitive and inlined replacement for clojure.core/*.
Parameters:
long.Returns the product as a long, following standard JVM two's complement overflow wraparound. With no arguments returns 1. With one argument returns it unchanged.
Multiplies numbers together, coercing arguments and the result to `long`. Primitive and inlined replacement for `clojure.core/*`. Parameters: - zero or more values coercible to `long`. Returns the product as a long, following standard JVM two's complement overflow wraparound. With no arguments returns `1`. With one argument returns it unchanged. See also [[*]] (double version), [[long-add]], [[long-sub]], [[long-div]].
(long-quot x y)Primitive and inlined quot coerced to longs
Primitive and inlined `quot` coerced to longs
(long-rem x y)Primitive and inlined rem coerced to longs
Primitive and inlined `rem` coerced to longs
(long-sub a)(long-sub a b)(long-sub a b c)(long-sub a b c d)(long-sub a b c d & r)Subtracts numbers, or negates a single value, coercing arguments and the result to long. Primitive and inlined replacement for clojure.core/-.
Parameters:
long.Returns the negation of the sole argument when called with one value, otherwise the left-to-right cumulative subtraction of all arguments, as a long, following standard JVM two's complement overflow wraparound.
Subtracts numbers, or negates a single value, coercing arguments and the result to `long`. Primitive and inlined replacement for `clojure.core/-`. Parameters: - one or more values coercible to `long`. Returns the negation of the sole argument when called with one value, otherwise the left-to-right cumulative subtraction of all arguments, as a long, following standard JVM two's complement overflow wraparound. See also [[-]] (double version), [[long-add]], [[long-mult]], [[long-div]].
(low-2-exp x)Finds the greatest integer n such that 2^n does not exceed the absolute value of x.
Equivalent to the floor of the base-2 logarithm of |x|. Together with high-2-exp it brackets |x| between two consecutive powers of two.
Computed bit-exactly from x's IEEE 754 exponent field (not via a floating-point logarithm), so it is exact for every finite, normal double, including exact powers of two. Contrast with low-exp (arbitrary base), which has no such bit-exact shortcut and can be off by one at exact powers of b due to floating-point logarithm error.
Parameters:
x (double): Input value.Returns the exponent n as a long. Returns -1023 for x equal to 0.0 or subnormal (matches the underlying getExponent convention; not a meaningful power-of-two bracket in that case).
See also high-2-exp, low-exp.
Finds the greatest integer `n` such that `2^n` does not exceed the absolute value of `x`. Equivalent to the floor of the base-2 logarithm of `|x|`. Together with [[high-2-exp]] it brackets `|x|` between two consecutive powers of two. Computed bit-exactly from `x`'s IEEE 754 exponent field (not via a floating-point logarithm), so it is exact for every finite, normal double, including exact powers of two. Contrast with [[low-exp]] (arbitrary base), which has no such bit-exact shortcut and can be off by one at exact powers of `b` due to floating-point logarithm error. Parameters: - `x` (double): Input value. Returns the exponent `n` as a long. Returns `-1023` for `x` equal to `0.0` or subnormal (matches the underlying `getExponent` convention; not a meaningful power-of-two bracket in that case). See also [[high-2-exp]], [[low-exp]].
(low-exp b x)Finds the greatest integer n such that b^n does not exceed the absolute value of x.
Equivalent to the floor of the base-b logarithm of |x|. Together with high-exp it brackets |x| between two consecutive powers of b.
Parameters:
b (double): Base, must be positive and not equal to 1.0.x (double): Input value.Returns the exponent n as a long.
Computed by rounding the (floating-point, therefore imprecise) base-b logarithm to the nearest integer, then verifying that candidate against b^n directly and correcting by one if needed -- this avoids the systematic off-by-one a plain floor(logb x) has at an exact power of b (there is no bit-exact shortcut for an arbitrary base, unlike low-2-exp for base 2).
Finds the greatest integer `n` such that `b^n` does not exceed the absolute value of `x`. Equivalent to the floor of the base-`b` logarithm of `|x|`. Together with [[high-exp]] it brackets `|x|` between two consecutive powers of `b`. Parameters: - `b` (double): Base, must be positive and not equal to `1.0`. - `x` (double): Input value. Returns the exponent `n` as a long. Computed by rounding the (floating-point, therefore imprecise) base-`b` logarithm to the nearest integer, then verifying that candidate against `b^n` directly and correcting by one if needed -- this avoids the systematic off-by-one a plain `floor(logb x)` has at an exact power of `b` (there is no bit-exact shortcut for an arbitrary base, unlike [[low-2-exp]] for base 2). See also [[high-exp]], [[low-2-exp]].
(make-norm start stop)(make-norm start stop dstart dstop)Creates a reusable function that linearly maps values from a fixed source range.
This is a partially applied version of norm, useful when the same source range (and optionally the same target range) is reused for many values, avoiding repeated range arguments.
Parameters:
start, stop (doubles): Fixed source range.dstart, dstop (doubles): Fixed target range. When omitted, the returned function accepts them on every call.Returns a function of a double value v to a double. When dstart and dstop are not provided here, the returned function has arity [v dstart dstop]; when they are provided, the returned function has arity [v].
Creates a reusable function that linearly maps values from a fixed source range. This is a partially applied version of [[norm]], useful when the same source range (and optionally the same target range) is reused for many values, avoiding repeated range arguments. Parameters: - `start`, `stop` (doubles): Fixed source range. - `dstart`, `dstop` (doubles): Fixed target range. When omitted, the returned function accepts them on every call. Returns a function of a `double` value `v` to a `double`. When `dstart` and `dstop` are not provided here, the returned function has arity `[v dstart dstop]`; when they are provided, the returned function has arity `[v]`. See also [[norm]], [[mnorm]].
(max a)(max a b)(max a b c)(max a b c d)(max a b c d & r)Returns the largest of one or more values. Primitive and inlined replacement for clojure.core/max.
Parameters:
double values.Returns the maximum value as a double.
Note: a direct call with all-integer arguments is compiled via :inline and can return a long instead; called indirectly (apply, reduce, higher-order use), the result always follows this function's declared double signature. Value identical either way, only the type differs.
Returns the largest of one or more values. Primitive and inlined replacement for `clojure.core/max`. Parameters: - one or more `double` values. Returns the maximum value as a double. Note: a direct call with all-integer arguments is compiled via `:inline` and can return a `long` instead; called indirectly (`apply`, `reduce`, higher-order use), the result always follows this function's declared `double` signature. Value identical either way, only the type differs. See also [[long-max]] (long-coerced version), [[min]].
(min a)(min a b)(min a b c)(min a b c d)(min a b c d & r)Returns the smallest of one or more values. Primitive and inlined replacement for clojure.core/min.
Parameters:
double values.Returns the minimum value as a double.
Note: a direct call with all-integer arguments is compiled via :inline and can return a long instead; called indirectly (apply, reduce, higher-order use), the result always follows this function's declared double signature. Value identical either way, only the type differs.
Returns the smallest of one or more values. Primitive and inlined replacement for `clojure.core/min`. Parameters: - one or more `double` values. Returns the minimum value as a double. Note: a direct call with all-integer arguments is compiled via `:inline` and can return a `long` instead; called indirectly (`apply`, `reduce`, higher-order use), the result always follows this function's declared `double` signature. Value identical either way, only the type differs. See also [[long-min]] (long-coerced version), [[max]].
(mlerp start stop t)lerp as macro. For inline code. See also lerp, cos-interpolation, quad-interpolation or smooth-interpolation.
[[lerp]] as macro. For inline code. See also [[lerp]], [[cos-interpolation]], [[quad-interpolation]] or [[smooth-interpolation]].
(mnorm v start stop)(mnorm v start1 stop1 start2 stop2)norm as a macro, for inline code -- same semantics and arities (3-arity normalizes to [0,1], 5-arity maps between two arbitrary ranges), including the degenerate-source-range corner case.
See also norm.
[[norm]] as a macro, for inline code -- same semantics and arities (3-arity normalizes to `[0,1]`, 5-arity maps between two arbitrary ranges), including the degenerate-source-range corner case. See also [[norm]].
(most-significant-bit v)Returns the most significant bit position. Can be treated as floor(log2(v)) for positive, integer v.
Returns -1 for 0 and 63 for negative numbers.
Returns the most significant bit position. Can be treated as floor(log2(v)) for positive, integer `v`. Returns `-1` for `0` and `63` for negative numbers.
(mpow x e m)Calculates modular exponentiation, that is x raised to the power e, reduced modulo m.
Uses binary (square-and-multiply) exponentiation, so it runs efficiently even for large exponents.
Parameters:
x (long): Base.e (long): Exponent, must be non-negative.m (long): Modulus, must be positive.Returns the result as a long in the range [0, m-1]. Returns 0 when m is 1.
Calculates modular exponentiation, that is `x` raised to the power `e`, reduced modulo `m`. Uses binary (square-and-multiply) exponentiation, so it runs efficiently even for large exponents. Parameters: - `x` (long): Base. - `e` (long): Exponent, must be non-negative. - `m` (long): Modulus, must be positive. Returns the result as a long in the range `[0, m-1]`. Returns `0` when `m` is `1`. See also [[fpow]], [[pow]].
(muladd x y z)Computes x*y + z using fused multiply-add when available.
Parameters:
x, y, z (doubles): multiplicands and addend.Returns x*y + z as a double. On Java 9+, uses Math/fma for a single correctly-rounded fused multiply-add (more accurate than a separate multiply and add). On earlier JVMs, falls back to a plain (+ z (* x y)) with intermediate rounding.
See also fma (identical implementation), negmuladd, difference-of-products, sum-of-products.
Computes `x*y + z` using fused multiply-add when available. Parameters: - `x`, `y`, `z` (doubles): multiplicands and addend. Returns `x*y + z` as a double. On Java 9+, uses `Math/fma` for a single correctly-rounded fused multiply-add (more accurate than a separate multiply and add). On earlier JVMs, falls back to a plain `(+ z (* x y))` with intermediate rounding. See also [[fma]] (identical implementation), [[negmuladd]], [[difference-of-products]], [[sum-of-products]].
(near-zero? x)(near-zero? x abs-tol)(near-zero? x abs-tol rel-tol)Checks whether x is close enough to zero to be treated as zero.
Parameters:
x (double): the value to check.abs-tol (double, optional, default 1.0e-6): absolute tolerance.rel-tol (double, optional, default 0.0): relative tolerance, scaled by (abs x) itself.Returns true if (abs x) is less than (max abs-tol (* rel-tol (abs x))), false otherwise.
Since the relative-tolerance term is scaled by x's own magnitude, it can only widen the threshold beyond abs-tol when rel-tol is 1.0 or greater -- for any smaller (i.e. any realistic) rel-tol, the 3-arity form behaves identically to the 2-arity form and rel-tol has no effect. This mirrors the standard convention that a relative tolerance compared against a target of zero contributes nothing.
See also delta-eq.
Checks whether `x` is close enough to zero to be treated as zero. Parameters: - `x` (double): the value to check. - `abs-tol` (double, optional, default `1.0e-6`): absolute tolerance. - `rel-tol` (double, optional, default `0.0`): relative tolerance, scaled by `(abs x)` itself. Returns `true` if `(abs x)` is less than `(max abs-tol (* rel-tol (abs x)))`, `false` otherwise. Since the relative-tolerance term is scaled by `x`'s own magnitude, it can only widen the threshold beyond `abs-tol` when `rel-tol` is `1.0` or greater -- for any smaller (i.e. any realistic) `rel-tol`, the 3-arity form behaves identically to the 2-arity form and `rel-tol` has no effect. This mirrors the standard convention that a relative tolerance compared against a target of zero contributes nothing. See also [[delta-eq]].
(neg-inf? v)Checks whether v is negative infinity.
Parameters:
v (double): the value to check.Returns true only for ##-Inf; false for ##Inf, NaN, and every finite value.
Checks whether `v` is negative infinity. Parameters: - `v` (double): the value to check. Returns `true` only for `##-Inf`; `false` for `##Inf`, `NaN`, and every finite value. See also [[pos-inf?]], [[inf?]].
(negative-zero? x)Checks whether a double is negative zero (-0.0), as distinct from positive zero (0.0).
Parameters:
x (double): value to check.Returns true when x is bitwise equal to -0.0, false otherwise (including for 0.0, despite (== -0.0 0.0) being true under normal floating-point equality).
See also zero?.
Checks whether a double is negative zero (`-0.0`), as distinct from positive zero (`0.0`). Parameters: - `x` (double): value to check. Returns `true` when `x` is bitwise equal to `-0.0`, `false` otherwise (including for `0.0`, despite `(== -0.0 0.0)` being `true` under normal floating-point equality). See also [[zero?]].
(negmuladd x y z)Computes -x*y + z (negated fused multiply-add) using fused multiply-add when available.
Parameters:
x, y, z (doubles): multiplicands (negated) and addend.Returns -x*y + z as a double. On Java 9+, uses Math/fma for a single correctly-rounded fused multiply-add. On earlier JVMs, falls back to a plain (+ z (* (- x) y)) with intermediate rounding.
Computes `-x*y + z` (negated fused multiply-add) using fused multiply-add when available. Parameters: - `x`, `y`, `z` (doubles): multiplicands (negated) and addend. Returns `-x*y + z` as a double. On Java 9+, uses `Math/fma` for a single correctly-rounded fused multiply-add. On earlier JVMs, falls back to a plain `(+ z (* (- x) y))` with intermediate rounding. See also [[muladd]], [[fma]].
(next-double v)(next-double v delta)Returns the closest representable double value greater than v, moving toward positive infinity.
This steps v by one ulp (unit in the last place). The optional delta argument repeats the step delta times, moving further away from v.
Parameters:
v (double): Starting value.delta (long): Number of steps to take, must be non-negative. Defaults to 1.Returns the resulting double value.
Returns NaN when v is NaN. Returns ##Inf when v is ##Inf.
See also prev-double.
Returns the closest representable double value greater than `v`, moving toward positive infinity. This steps `v` by one ulp (unit in the last place). The optional `delta` argument repeats the step `delta` times, moving further away from `v`. Parameters: - `v` (double): Starting value. - `delta` (long): Number of steps to take, must be non-negative. Defaults to `1`. Returns the resulting double value. Returns `NaN` when `v` is `NaN`. Returns `##Inf` when `v` is `##Inf`. See also [[prev-double]].
(norm v start stop)(norm v start1 stop1 start2 stop2)Linearly maps v from one range to another.
With two arities: the 3-argument form normalizes v from the range [start,stop] to [0,1]. The 5-argument form maps v from the range [start1,stop1] to the range [start2,stop2]. Both forms are equivalent to a linear interpolation and extrapolate when v lies outside the source range.
Parameters:
v (double): Value to map.start, stop (doubles): Source range for the 3-arity normalization to [0,1].start1, stop1 (doubles): Source range for the 5-arity mapping.start2, stop2 (doubles): Target range for the 5-arity mapping.Returns the mapped value as a double.
When the source range is degenerate (start equal to stop), avoids dividing by zero by returning 0.0 for v<=start and 1.0 for v>start (and, for the 5-arity form, the corresponding endpoint of the target range) instead of NaN/##Inf.
See also mnorm (macro version), make-norm (returns a reusable mapping function), constrain (clamps a value to a range).
Linearly maps `v` from one range to another. With two arities: the 3-argument form normalizes `v` from the range `[start,stop]` to `[0,1]`. The 5-argument form maps `v` from the range `[start1,stop1]` to the range `[start2,stop2]`. Both forms are equivalent to a linear interpolation and extrapolate when `v` lies outside the source range. Parameters: - `v` (double): Value to map. - `start`, `stop` (doubles): Source range for the 3-arity normalization to `[0,1]`. - `start1`, `stop1` (doubles): Source range for the 5-arity mapping. - `start2`, `stop2` (doubles): Target range for the 5-arity mapping. Returns the mapped value as a double. When the source range is degenerate (`start` equal to `stop`), avoids dividing by zero by returning `0.0` for `v<=start` and `1.0` for `v>start` (and, for the 5-arity form, the corresponding endpoint of the target range) instead of `NaN`/`##Inf`. See also [[mnorm]] (macro version), [[make-norm]] (returns a reusable mapping function), [[constrain]] (clamps a value to a range).
(not-neg? x)Primitive and inlined not-neg? (x>=0.0)
Primitive and inlined `not-neg?` (x>=0.0)
(not-pos? x)Primitive and inlined not-pos? (x<=0.0)
Primitive and inlined `not-pos?` (x<=0.0)
(not== _)(not== a b)(not== a b & r)Not equality. For more than two arguments, returns true when all values are unique.
(not== 1 2 1) === (and (not= 1 1) (not= 1 2))
Parameters:
double values.Returns true when all arguments are pairwise distinct, false when any two arguments are equal, as a Boolean. With one argument returns false.
Not equality. For more than two arguments, returns `true` when all values are unique. `(not== 1 2 1)` === `(and (not= 1 1) (not= 1 2))` Parameters: - one or more `double` values. Returns `true` when all arguments are pairwise distinct, `false` when any two arguments are equal, as a Boolean. With one argument returns `false`. See also [[==]], [[eq]].
(one? x)Primitive and inlined one? (x==1.0)
Primitive and inlined `one?` (x==1.0)
(order vs)(order vs decreasing?)Computes the permutation of indices that would sort the input collection vs.
The result is a sequence of 0-based indices such that applying them to the original collection
using (map #(nth vs %) result) yields a sorted sequence.
Arguments:
vs: A collection of comparable values.decreasing?: Optional boolean (default false). If true, the indices permute for a descending sort.Returns: A sequence of 0-based indices.
Computes the permutation of indices that would sort the input collection `vs`. The result is a sequence of 0-based indices such that applying them to the original collection using `(map #(nth vs %) result)` yields a sorted sequence. Arguments: - `vs`: A collection of comparable values. - `decreasing?`: Optional boolean (default false). If true, the indices permute for a descending sort. Returns: A sequence of 0-based indices.
(pos-inf? v)Checks whether v is positive infinity.
Parameters:
v (double): the value to check.Returns true only for ##Inf; false for ##-Inf, NaN, and every finite value.
Checks whether `v` is positive infinity. Parameters: - `v` (double): the value to check. Returns `true` only for `##Inf`; `false` for `##-Inf`, `NaN`, and every finite value. See also [[neg-inf?]], [[inf?]].
(pow10 x)Computes x^10.
Parameters:
x (double): value to raise to the 10th power.Returns the result as a double, computed as ((x^3)^3)*x to minimize the number of multiplications.
Computes `x^10`. Parameters: - `x` (double): value to raise to the 10th power. Returns the result as a double, computed as `((x^3)^3)*x` to minimize the number of multiplications. See also [[pow]], [[pow3]].
(pow2 x)Computes x^2 (x*x). Identical implementation to sq.
Parameters:
x (double): value to square.Returns the result as a double.
Computes `x^2` (`x*x`). Identical implementation to [[sq]]. Parameters: - `x` (double): value to square. Returns the result as a double. See also [[sq]], [[pow3]], [[pow]].
(pow3 x)Computes x^3 (x*x*x). Identical implementation to cb.
Parameters:
x (double): value to cube.Returns the result as a double.
Computes `x^3` (`x*x*x`). Identical implementation to [[cb]]. Parameters: - `x` (double): value to cube. Returns the result as a double. See also [[cb]], [[pow2]], [[pow]].
(power-of-two? v)Checks whether v is an exact power of two, i.e. v = 2^p for some non-negative integer p.
Parameters:
v (long): the value to check.Returns true if v is positive and has exactly one bit set, false otherwise (including for v<=0).
See also round-up-pow2.
Checks whether `v` is an exact power of two, i.e. `v = 2^p` for some non-negative integer `p`. Parameters: - `v` (long): the value to check. Returns `true` if `v` is positive and has exactly one bit set, `false` otherwise (including for `v<=0`). See also [[round-up-pow2]].
(prev-double v)(prev-double v delta)Returns the closest representable double value smaller than v, moving toward negative infinity.
This steps v by one ulp (unit in the last place). The optional delta argument repeats the step delta times, moving further away from v.
Parameters:
v (double): Starting value.delta (long): Number of steps to take, must be non-negative. Defaults to 1.Returns the resulting double value.
Returns NaN when v is NaN. Returns ##-Inf when v is ##-Inf.
See also next-double.
Returns the closest representable double value smaller than `v`, moving toward negative infinity. This steps `v` by one ulp (unit in the last place). The optional `delta` argument repeats the step `delta` times, moving further away from `v`. Parameters: - `v` (double): Starting value. - `delta` (long): Number of steps to take, must be non-negative. Defaults to `1`. Returns the resulting double value. Returns `NaN` when `v` is `NaN`. Returns `##-Inf` when `v` is `##-Inf`. See also [[next-double]].
(qceil x)Fast version of ceil. Returns long.
Fast version of [[ceil]]. Returns `long`.
(qdist [x1 y1] [x2 y2])(qdist x1 y1 x2 y2)Computes the Euclidean distance between two 2D points, using qsqrt instead of sqrt for a faster, less accurate result.
Parameters:
[x1 y1], [x2 y2] (pairs of doubles): the two points, for the 2-arity form.x1, y1, x2, y2 (doubles): the two points' coordinates directly, for the 4-arity form.Returns the approximate distance as a double.
Computes the Euclidean distance between two 2D points, using [[qsqrt]] instead of `sqrt` for a faster, less accurate result. Parameters: - `[x1 y1]`, `[x2 y2]` (pairs of doubles): the two points, for the 2-arity form. - `x1`, `y1`, `x2`, `y2` (doubles): the two points' coordinates directly, for the 4-arity form. Returns the approximate distance as a double. See also [[dist]], [[qsqrt]].
(qexp x)Quick and less accurate version of exp.
Quick and less accurate version of [[exp]].
(qfloor x)Fast version of floor. Returns long.
Fast version of [[floor]]. Returns `long`.
(qlog x)Fast and less accurate version of log.
Fast and less accurate version of [[log]].
(qpow x exponent)Fast and less accurate version of pow.
Fast and less accurate version of [[pow]].
(qround x)Fast version of round. Returns long
Fast version of [[round]]. Returns `long`
(qsqrt x)Approximated sqrt using binary operations with error 1.0E-2.
Approximated [[sqrt]] using binary operations with error `1.0E-2`.
(quad-interpolation start stop t)Interpolates between start and stop following a piecewise quadratic ease-in-ease-out curve, for amount t.
Parameters:
start, stop (doubles): the two endpoints.t (double): interpolation amount, typically in [0,1].Returns start when t=0, stop when t=1, easing quadratically in over the first half (t<0.5) and quadratically out over the second half, meeting continuously at t=0.5.
See also lerp/mlerp (linear), cos-interpolation, smooth-interpolation (other easing curves).
Interpolates between `start` and `stop` following a piecewise quadratic ease-in-ease-out curve, for amount `t`. Parameters: - `start`, `stop` (doubles): the two endpoints. - `t` (double): interpolation amount, typically in `[0,1]`. Returns `start` when `t=0`, `stop` when `t=1`, easing quadratically in over the first half (`t<0.5`) and quadratically out over the second half, meeting continuously at `t=0.5`. See also [[lerp]]/[[mlerp]] (linear), [[cos-interpolation]], [[smooth-interpolation]] (other easing curves).
(radians deg)Converts an angle from degrees to radians.
Parameters:
deg (double): angle in degrees.Returns the angle in radians as a double.
See also degrees.
Converts an angle from degrees to radians. Parameters: - `deg` (double): angle in degrees. Returns the angle in radians as a double. See also [[degrees]].
(rank vs)(rank vs ties)(rank vs ties desc?)Assigns ranks to values in a collection, handling ties according to a specified strategy. Ranks are 0-based indices indicating the position of each element in the sorted collection.
Arguments:
vs: A collection of comparable values.ties: The tie-breaking strategy (keyword, optional, default :average).
Supported strategies:
:average: Assign the average rank to all tied values.:first: Assign ranks based on their appearance order in the input.:last: Assign ranks based on their appearance order in the input (reverse of :first).:random: Assign random ranks to tied values.:min: Assign the minimum rank to all tied values.:max: Assign the maximum rank to all tied values.:dense: Assign consecutive ranks without gaps (like data.table::frank in R).desc?: If true, rank in descending order (boolean, optional, default false).Returns a sequence of rank values corresponding to the input elements.
Assigns ranks to values in a collection, handling ties according to a specified strategy. Ranks are 0-based indices indicating the position of each element in the sorted collection. Arguments: - `vs`: A collection of comparable values. - `ties`: The tie-breaking strategy (keyword, optional, default `:average`). Supported strategies: - `:average`: Assign the average rank to all tied values. - `:first`: Assign ranks based on their appearance order in the input. - `:last`: Assign ranks based on their appearance order in the input (reverse of `:first`). - `:random`: Assign random ranks to tied values. - `:min`: Assign the minimum rank to all tied values. - `:max`: Assign the maximum rank to all tied values. - `:dense`: Assign consecutive ranks without gaps (like `data.table::frank` in R). - `desc?`: If true, rank in descending order (boolean, optional, default `false`). Returns a sequence of rank values corresponding to the input elements.
(relative-error v v-approx)Calculates the relative error between a true value and an approximation.
Parameters:
v (double): the true (reference) value. Used as the divisor.v-approx (double): the approximate value.Returns (abs (/ (- v v-approx) v)), i.e. the absolute error scaled by (abs v). Not symmetric: swapping v and v-approx changes the divisor. Returns ##Inf when v is 0.0 and v-approx is not, and ##NaN when both are 0.0.
See also absolute-error.
Calculates the relative error between a true value and an approximation. Parameters: - `v` (double): the true (reference) value. Used as the divisor. - `v-approx` (double): the approximate value. Returns `(abs (/ (- v v-approx) v))`, i.e. the absolute error scaled by `(abs v)`. Not symmetric: swapping `v` and `v-approx` changes the divisor. Returns `##Inf` when `v` is `0.0` and `v-approx` is not, and `##NaN` when both are `0.0`. See also [[absolute-error]].
(remainder dividend divisor)IEEE 754 remainder (Math/IEEEremainder): returns dividend - divisor * n,
where n is the mathematical integer closest to dividend/divisor (when two integers are equally close, the even one). Returned value in [-|divisor|/2,|divisor|/2]
IEEE 754 remainder (`Math/IEEEremainder`): returns dividend - divisor * n, where n is the mathematical integer closest to dividend/divisor (when two integers are equally close, the even one). Returned value in `[-|divisor|/2,|divisor|/2]`
(rint x)(rint x scale)Rounds x to the nearest integer, returned as a double, using round-half-to-even.
Parameters:
x (double): the number to round.scale (double, optional): if given, x is divided by scale, rounded, then multiplied back by scale -- i.e. rounds to the nearest multiple of scale, ties rounding to even.Returns the rounded value as a double.
See also round, round-even, qround.
Rounds `x` to the nearest integer, returned as a double, using round-half-to-even. Parameters: - `x` (double): the number to round. - `scale` (double, optional): if given, `x` is divided by `scale`, rounded, then multiplied back by `scale` -- i.e. rounds to the nearest multiple of `scale`, ties rounding to even. Returns the rounded value as a double. See also [[round]], [[round-even]], [[qround]].
(rising-factorial n x)Calculates the rising (ascending) factorial of x to the power n, also known as the Pochhammer symbol.
Defined as the product x*(x+1)*(x+2)*...*(x+n-1) for a non-negative integer n. When n is not a non-negative integer, the definition is extended using the gamma function.
Parameters:
n (double): Number of ascending terms.x (double): Starting value.Returns the rising factorial as a double.
See also falling-factorial, rising-factorial-int, factorial, combinations.
Calculates the rising (ascending) factorial of `x` to the power `n`, also known as the Pochhammer symbol. Defined as the product `x*(x+1)*(x+2)*...*(x+n-1)` for a non-negative integer `n`. When `n` is not a non-negative integer, the definition is extended using the gamma function. Parameters: - `n` (double): Number of ascending terms. - `x` (double): Starting value. Returns the rising factorial as a double. See also [[falling-factorial]], [[rising-factorial-int]], [[factorial]], [[combinations]].
(rising-factorial-int n x)Computes the rising (ascending, Pochhammer) factorial of x to the power of an integer n, x*(x+1)*...*(x+n-1).
Parameters:
n (long): number of ascending terms; may be negative, in which case the result is the reciprocal of the rising factorial with n negated and x shifted by n.x (double): starting value.Returns the rising factorial as a double.
See also rising-factorial, falling-factorial-int.
Computes the rising (ascending, Pochhammer) factorial of `x` to the power of an integer `n`, `x*(x+1)*...*(x+n-1)`. Parameters: - `n` (long): number of ascending terms; may be negative, in which case the result is the reciprocal of the rising factorial with `n` negated and `x` shifted by `n`. - `x` (double): starting value. Returns the rising factorial as a double. See also [[rising-factorial]], [[falling-factorial-int]].
(round-even x)Round evenly, IEEE / IEC rounding
Round evenly, IEEE / IEC rounding
(round-up-pow2 v)Rounds v up to the smallest power of two greater than or equal to it.
Parameters:
v (long): a positive value.Returns the smallest 2^p >= v as a long. Undefined for v<=0 (not documented/guarded). Overflows silently to Long/MIN_VALUE for any v greater than 2^62 (4611686018427387904), since the true result 2^63 cannot be represented in a signed 64-bit long.
See also power-of-two?.
Rounds `v` up to the smallest power of two greater than or equal to it. Parameters: - `v` (long): a positive value. Returns the smallest `2^p >= v` as a `long`. Undefined for `v<=0` (not documented/guarded). Overflows silently to `Long/MIN_VALUE` for any `v` greater than `2^62` (`4611686018427387904`), since the true result `2^63` cannot be represented in a signed 64-bit `long`. See also [[power-of-two?]].
(rqsqrt x)Reciprocal of qsqrt. Quick and less accurate.
Reciprocal of [[qsqrt]]. Quick and less accurate.
(safe-sqrt value)Computes sqrt(x), returning 0.0 instead of ##NaN for negative x.
Parameters:
value (double): value to take the square root of.Returns the result as a double, 0.0 when value is negative.
Computes `sqrt(x)`, returning `0.0` instead of `##NaN` for negative `x`. Parameters: - `value` (double): value to take the square root of. Returns the result as a double, `0.0` when `value` is negative. See also [[sqrt]], [[qsqrt]].
(sample f number-of-values)(sample f number-of-values domain?)(sample f domain-min domain-max number-of-values)(sample f domain-min domain-max number-of-values domain?)Samples a function f by evaluating it at evenly spaced points within a numerical range.
Generates number-of-values points in the specified range [domain-min, domain-max] (inclusive) and applies f to each point.
Arguments:
f: The function to sample. Should accept a single double argument.number-of-values: The total number of points to generate (a positive long).domain-min: The lower bound of the sampling range (a double). Defaults to 0.0.domain-max: The upper bound of the sampling range (a double). Defaults to 1.0.domain?: A boolean flag. If true, returns pairs [x, (f x)]. If false (default), returns just (f x).Arities:
[f number-of-values]: Samples f in [0.0, 1.0]. Returns (f x) values.[f number-of-values domain?]: Samples f in [0.0, 1.0]. Returns [x, (f x)] pairs if domain? is true, otherwise (f x) values.[f domain-min domain-max number-of-values]: Samples f in [domain-min, domain-max]. Returns (f x) values.[f domain-min domain-max number-of-values domain?]: Samples f in [domain-min, domain-max]. Returns [x, (f x)] pairs if domain? is true, otherwise (f x) values.The points are generated linearly from domain-min to domain-max. If number-of-values is 1, it samples only the midpoint of the range.
Returns a sequence of double values or vectors [double, double] depending on domain?.
Samples a function `f` by evaluating it at evenly spaced points within a numerical range. Generates `number-of-values` points in the specified range `[domain-min, domain-max]` (inclusive) and applies `f` to each point. Arguments: - `f`: The function to sample. Should accept a single `double` argument. - `number-of-values`: The total number of points to generate (a positive `long`). - `domain-min`: The lower bound of the sampling range (a `double`). Defaults to `0.0`. - `domain-max`: The upper bound of the sampling range (a `double`). Defaults to `1.0`. - `domain?`: A boolean flag. If `true`, returns pairs `[x, (f x)]`. If `false` (default), returns just `(f x)`. Arities: - `[f number-of-values]`: Samples `f` in `[0.0, 1.0]`. Returns `(f x)` values. - `[f number-of-values domain?]`: Samples `f` in `[0.0, 1.0]`. Returns `[x, (f x)]` pairs if `domain?` is true, otherwise `(f x)` values. - `[f domain-min domain-max number-of-values]`: Samples `f` in `[domain-min, domain-max]`. Returns `(f x)` values. - `[f domain-min domain-max number-of-values domain?]`: Samples `f` in `[domain-min, domain-max]`. Returns `[x, (f x)]` pairs if `domain?` is true, otherwise `(f x)` values. The points are generated linearly from `domain-min` to `domain-max`. If `number-of-values` is 1, it samples only the midpoint of the range. Returns a sequence of `double` values or vectors `[double, double]` depending on `domain?`.
(scalb x n)Scales x by a power of two, x * 2^n, without computing 2^n.
The result is exact unless it is subnormal (then it is rounded as by a floating point multiplication) or out of the range of a double.
Parameters:
x (double): value to scale.n (long): the exponent of the power of two. A value outside the range of an int is treated as the nearest int limit, which already gives an infinity or a zero for any finite non-zero x.Returns x * 2^n as a double. Overflow gives ##Inf or ##-Inf, underflow gives 0.0 or -0.0. Zero, infinity and ##NaN are returned unchanged (a zero keeps its sign).
See also ulp, double-exponent.
Scales `x` by a power of two, `x * 2^n`, without computing `2^n`. The result is exact unless it is subnormal (then it is rounded as by a floating point multiplication) or out of the range of a double. Parameters: - `x` (double): value to scale. - `n` (long): the exponent of the power of two. A value outside the range of an `int` is treated as the nearest `int` limit, which already gives an infinity or a zero for any finite non-zero `x`. Returns `x * 2^n` as a double. Overflow gives `##Inf` or `##-Inf`, underflow gives `0.0` or `-0.0`. Zero, infinity and `##NaN` are returned unchanged (a zero keeps its sign). See also [[ulp]], [[double-exponent]].
(sec x)Computes the secant of x, sec(x) = 1/cos(x).
Parameters:
x (double): angle in radians.Returns sec(x) as a double. Diverges where cos(x) is zero, i.e. at odd multiples of π/2.
Computes the secant of `x`, `sec(x) = 1/cos(x)`. Parameters: - `x` (double): angle in radians. Returns `sec(x)` as a double. Diverges where `cos(x)` is zero, i.e. at odd multiples of π/2. See also [[cos]], [[secpi]], [[cot]], [[csc]].
(sech x)Computes the hyperbolic secant of x, sech(x) = 1/cosh(x).
Parameters:
x (double): value to take the hyperbolic secant of.Returns sech(x) as a double, always in (0, 1].
Computes the hyperbolic secant of `x`, `sech(x) = 1/cosh(x)`. Parameters: - `x` (double): value to take the hyperbolic secant of. Returns `sech(x)` as a double, always in `(0, 1]`. See also [[cosh]], [[coth]], [[csch]].
(secpi x)Computes the secant of x expressed in half-turns (units of π), sec(π·x) = 1/cos(π·x).
Parameters:
x (double): value in half-turns.Returns sec(π·x) as a double, the reciprocal of cospi: ##Inf at every half-integer x, exactly 1.0 or -1.0 at integers. Infinite or NaN x gives ##NaN.
Computes the secant of `x` expressed in half-turns (units of π), `sec(π·x) = 1/cos(π·x)`. Parameters: - `x` (double): value in half-turns. Returns `sec(π·x)` as a double, the reciprocal of [[cospi]]: `##Inf` at every half-integer `x`, exactly `1.0` or `-1.0` at integers. Infinite or NaN `x` gives `##NaN`. See also [[sec]], [[cospi]], [[cotpi]], [[cscpi]].
(seq->double-array vs)Converts vs to a primitive double[] array.
Parameters:
vs: a sequence of numbers, a single number, nil, or an already-a-double[] array.Returns vs unchanged (no copy) if it is already a double[] array. Returns nil if vs is nil. Wraps a bare (non-seqable) number into a 1-element array. Otherwise returns (double-array vs).
See also double-array->seq, double-array-type.
Converts `vs` to a primitive `double[]` array. Parameters: - `vs`: a sequence of numbers, a single number, `nil`, or an already-a-`double[]` array. Returns `vs` unchanged (no copy) if it is already a `double[]` array. Returns `nil` if `vs` is `nil`. Wraps a bare (non-seqable) number into a 1-element array. Otherwise returns `(double-array vs)`. See also [[double-array->seq]], [[double-array-type]].
(seq->double-double-array vss)Converts vss to a primitive double[][] array-of-arrays.
Parameters:
vss: a sequence of rows (each row a sequence of numbers), nil, or an already-a-double[][] array.Returns vss unchanged (no copy) if it is already a double[][] array. Returns nil if vss is nil. Otherwise converts each row via seq->double-array and collects them into a double[][] array.
See also double-double-array->seq, double-double-array-type.
Converts `vss` to a primitive `double[][]` array-of-arrays. Parameters: - `vss`: a sequence of rows (each row a sequence of numbers), `nil`, or an already-a-`double[][]` array. Returns `vss` unchanged (no copy) if it is already a `double[][]` array. Returns `nil` if `vss` is `nil`. Otherwise converts each row via [[seq->double-array]] and collects them into a `double[][]` array. See also [[double-double-array->seq]], [[double-double-array-type]].
(sfrac v)Signed fractional part of v.
Parameters:
v (double): the input value.Returns (- v (trunc v)), i.e. the part of v remaining after truncation towards zero, keeping v's sign. Always in the range (-1.0, 1.0).
See also frac for the unsigned version.
Signed fractional part of `v`. Parameters: - `v` (double): the input value. Returns `(- v (trunc v))`, i.e. the part of `v` remaining after truncation towards zero, keeping `v`'s sign. Always in the range `(-1.0, 1.0)`. See also [[frac]] for the unsigned version.
(sgn value)Returns -1 when value is negative, 1 otherwise. See also signum.
Returns -1 when `value` is negative, 1 otherwise. See also [[signum]].
(sigmoid x)Computes the sigmoid (standard logistic) function, sigmoid(x) = 1/(1+exp(-x)).
Parameters:
x (double): value to evaluate.Returns the result as a double, always in (0, 1).
Computes the sigmoid (standard logistic) function, `sigmoid(x) = 1/(1+exp(-x))`. Parameters: - `x` (double): value to evaluate. Returns the result as a double, always in `(0, 1)`. See also [[logistic]] (alias), [[logit]] (inverse).
(signum value)Returns 1 if value is > 0, 0 if it is 0, -1 otherwise. See also sgn.
Returns 1 if `value` is > 0, 0 if it is 0, -1 otherwise. See also [[sgn]].
(sinc v)Computes the normalized sinc function, sinc(x) = sin(pi*x)/(pi*x), with the removable singularity at x=0 handled explicitly.
Parameters:
v (double): value to evaluate.Returns the result as a double, in [-1, 1]. Returns exactly 1.0 for |pi*v| below 1.0e-8 (avoiding division by a near-zero denominator).
See also sin.
Computes the normalized sinc function, `sinc(x) = sin(pi*x)/(pi*x)`, with the removable singularity at `x=0` handled explicitly. Parameters: - `v` (double): value to evaluate. Returns the result as a double, in `[-1, 1]`. Returns exactly `1.0` for `|pi*v|` below `1.0e-8` (avoiding division by a near-zero denominator). See also [[sin]].
(sinpi x)Computes sin(π·x) -- the sine of x expressed in half-turns (units of π) rather than radians.
The argument is reduced exactly to the nearest integer before the sine is taken, so the result is accurate to about 1 ulp for any x, the error does not grow with |x|, and the identity values are exact.
Parameters:
x (double): value in half-turns to take the sine of.Returns sin(π·x) as a double. At every integer x the result is a zero with the sign of x (+0.0 or -0.0), at half-integers it is exactly 1.0 or -1.0. Infinite or NaN x gives ##NaN.
Computes `sin(π·x)` -- the sine of `x` expressed in half-turns (units of π) rather than radians. The argument is reduced exactly to the nearest integer before the sine is taken, so the result is accurate to about 1 ulp for any `x`, the error does not grow with `|x|`, and the identity values are exact. Parameters: - `x` (double): value in half-turns to take the sine of. Returns `sin(π·x)` as a double. At every integer `x` the result is a zero with the sign of `x` (`+0.0` or `-0.0`), at half-integers it is exactly `1.0` or `-1.0`. Infinite or NaN `x` gives `##NaN`. See also [[sin]], [[cospi]], [[tanpi]], [[cscpi]].
(slice-range cnt)(slice-range data cnt)(slice-range start end cnt)Generates a sequence of cnt evenly spaced double values covering a range.
The range can be given explicitly, derived from a collection of data, or defaults to [0.0, 1.0] when only cnt is provided.
Parameters:
[cnt] (long): Number of points; range defaults to [0.0, 1.0].[data cnt] (sequence, long): Range is [(min data), (max data)]. Non-finite values (NaN, infinities) are removed from data before computing the range.[start end cnt] (double, double, long): Explicit inclusive range [start, end].The resulting sequence is inclusive, i.e. it starts at start (or the derived minimum) and ends at end (or the derived maximum). When cnt is 1, a single value equal to the midpoint of the range is returned instead.
Returns a sequence of cnt doubles, or an empty sequence when cnt is 0.
See also make-norm.
Generates a sequence of `cnt` evenly spaced double values covering a range. The range can be given explicitly, derived from a collection of data, or defaults to `[0.0, 1.0]` when only `cnt` is provided. Parameters: - `[cnt]` (long): Number of points; range defaults to `[0.0, 1.0]`. - `[data cnt]` (sequence, long): Range is `[(min data), (max data)]`. Non-finite values (`NaN`, infinities) are removed from `data` before computing the range. - `[start end cnt]` (double, double, long): Explicit inclusive range `[start, end]`. The resulting sequence is inclusive, i.e. it starts at `start` (or the derived minimum) and ends at `end` (or the derived maximum). When `cnt` is `1`, a single value equal to the midpoint of the range is returned instead. Returns a sequence of `cnt` doubles, or an empty sequence when `cnt` is `0`. See also [[make-norm]].
(smooth-interpolation start stop t)Interpolates between start and stop following the classic smoothstep (Hermite) ease curve, for amount t.
Parameters:
start, stop (doubles): the two endpoints.t (double): interpolation amount, typically in [0,1].Returns start when t=0, stop when t=1, easing smoothly (zero slope at both ends) rather than linearly in between, via t*t*(3-2*t) as the effective interpolation amount. See also smoothstep, which applies this same curve but also normalizes and clamps its input to [0,1] first.
See also lerp/mlerp (linear), cos-interpolation, quad-interpolation (other easing curves).
Interpolates between `start` and `stop` following the classic smoothstep (Hermite) ease curve, for amount `t`. Parameters: - `start`, `stop` (doubles): the two endpoints. - `t` (double): interpolation amount, typically in `[0,1]`. Returns `start` when `t=0`, `stop` when `t=1`, easing smoothly (zero slope at both ends) rather than linearly in between, via `t*t*(3-2*t)` as the effective interpolation amount. See also [[smoothstep]], which applies this same curve but also normalizes and clamps its input to `[0,1]` first. See also [[lerp]]/[[mlerp]] (linear), [[cos-interpolation]], [[quad-interpolation]] (other easing curves).
(smooth-max xs)(smooth-max xs alpha)(smooth-max xs alpha family)Returns a smooth approximation of the maximum value over a sequence xs.
Unlike a hard max, this function is differentiable everywhere and is
controlled by the sharpness parameter alpha. As alpha increases toward
infinity, the result converges to the true maximum. Negative alpha values
produce a smooth minimum approximation (except for :p-norm).
Parameters:
xs (sequence of numbers): Input values.alpha (double): Sharpness parameter. Defaults to 2.0. Larger positive
values approximate the true maximum more closely; negative values approximate
the minimum (except :p-norm).family (keyword): Smoothing family to use. Defaults to :lse. Available families:
:lse - LogSumExp: numerically stable, globally smooth over all elements.:boltzmann - Boltzmann operator (weighted average); best suited for small alpha values.:mellowmax - like :lse but mean-normalised, independent of sequence length.:smu - smooth maximum unit; pairwise reduction, epsilon = 1/|alpha| controls the rounding radius.:p-norm - p-norm-based smooth absolute maximum; always returns non-negative values; does not act as smooth minimum for negative alpha.:sigmoid, :circular, :quadratic, :cubic, :quartic, :exponential - pairwise reductions based on Inigo Quilez smooth minimum kernels for SDFs.Returns the smooth maximum as a double. Infinite elements give the limits (for positive alpha any ##Inf gives ##Inf and ##-Inf elements contribute nothing, though :mellowmax still counts them in its mean; mirrored for negative alpha; :p-norm uses magnitudes), and the families do not overflow for large alpha * x. Any ##NaN gives ##NaN. A single element is returned as is (its magnitude for :p-norm); an empty xs gives 0.0 for :p-norm, ##-Inf for the other families (##Inf for negative alpha, the empty smooth minimum). An infinite alpha gives the hard maximum (minimum for ##-Inf); :p-norm the largest (smallest) magnitude.
See also logsumexp (used internally by the :lse and :mellowmax families).
Returns a smooth approximation of the maximum value over a sequence `xs`. Unlike a hard `max`, this function is differentiable everywhere and is controlled by the sharpness parameter `alpha`. As `alpha` increases toward infinity, the result converges to the true maximum. Negative `alpha` values produce a smooth minimum approximation (except for `:p-norm`). Parameters: - `xs` (sequence of numbers): Input values. - `alpha` (double): Sharpness parameter. Defaults to `2.0`. Larger positive values approximate the true maximum more closely; negative values approximate the minimum (except `:p-norm`). - `family` (keyword): Smoothing family to use. Defaults to `:lse`. Available families: - `:lse` - LogSumExp: numerically stable, globally smooth over all elements. - `:boltzmann` - Boltzmann operator (weighted average); best suited for small `alpha` values. - `:mellowmax` - like `:lse` but mean-normalised, independent of sequence length. - `:smu` - smooth maximum unit; pairwise reduction, epsilon `= 1/|alpha|` controls the rounding radius. - `:p-norm` - p-norm-based smooth absolute maximum; always returns non-negative values; does not act as smooth minimum for negative `alpha`. - `:sigmoid`, `:circular`, `:quadratic`, `:cubic`, `:quartic`, `:exponential` - pairwise reductions based on Inigo Quilez smooth minimum kernels for SDFs. Returns the smooth maximum as a double. Infinite elements give the limits (for positive `alpha` any `##Inf` gives `##Inf` and `##-Inf` elements contribute nothing, though `:mellowmax` still counts them in its mean; mirrored for negative `alpha`; `:p-norm` uses magnitudes), and the families do not overflow for large `alpha * x`. Any `##NaN` gives `##NaN`. A single element is returned as is (its magnitude for `:p-norm`); an empty `xs` gives `0.0` for `:p-norm`, `##-Inf` for the other families (`##Inf` for negative `alpha`, the empty smooth minimum). An infinite `alpha` gives the hard maximum (minimum for `##-Inf`); `:p-norm` the largest (smallest) magnitude. See also [[logsumexp]] (used internally by the `:lse` and `:mellowmax` families).
(smoothstep edge0 edge1 x)GL-style smoothstep: smoothly interpolates from 0.0 to 1.0 as x moves from edge0 to edge1.
Parameters:
edge0, edge1 (doubles): the two threshold edges.x (double): the value being thresholded/eased.Returns 0.0 for x<=edge0, 1.0 for x>=edge1, and the classic smoothstep (Hermite) ease curve t*t*(3-2*t) (with t the clamped normalized position of x between the edges) in between -- unlike smooth-interpolation, the input is clamped, never extrapolated.
See also smooth-interpolation (same curve, unclamped, arbitrary output range), cnorm.
GL-style [smoothstep](https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/smoothstep.xhtml): smoothly interpolates from `0.0` to `1.0` as `x` moves from `edge0` to `edge1`. Parameters: - `edge0`, `edge1` (doubles): the two threshold edges. - `x` (double): the value being thresholded/eased. Returns `0.0` for `x<=edge0`, `1.0` for `x>=edge1`, and the classic smoothstep (Hermite) ease curve `t*t*(3-2*t)` (with `t` the clamped normalized position of `x` between the edges) in between -- unlike [[smooth-interpolation]], the input is clamped, never extrapolated. See also [[smooth-interpolation]] (same curve, unclamped, arbitrary output range), [[cnorm]].
(spow x exponent)Computes the symmetric power of x, spow(x,e) = sign(x) * |x|^e, preserving the sign of x (e.g. allows fractional or even exponents on negative bases without producing ##NaN).
Parameters:
x (double): base.exponent (double): power to raise |x| to.Returns the result as a double, with the sign of x (or 0.0 when x is 0.0).
Computes the symmetric power of `x`, `spow(x,e) = sign(x) * |x|^e`, preserving the sign of `x` (e.g. allows fractional or even exponents on negative bases without producing `##NaN`). Parameters: - `x` (double): base. - `exponent` (double): power to raise `|x|` to. Returns the result as a double, with the sign of `x` (or `0.0` when `x` is `0.0`). See also [[pow]], [[qpow]].
(sq x)Computes x^2 (x*x).
Parameters:
x (double): value to square.Returns the result as a double.
Computes `x^2` (`x*x`). Parameters: - `x` (double): value to square. Returns the result as a double. See also [[pow2]] (identical implementation), [[cb]], [[pow]].
(stirling-factorial x)Approximates x! using Stirling's asymptotic series with a 6-term correction, without relying on the gamma function.
Parameters:
x (double): value to approximate the factorial of; accuracy improves for larger x (already near double-precision-level accuracy for x >= 5).Returns the approximate result as a double.
See also factorial, log-stirling-factorial.
Approximates `x!` using Stirling's asymptotic series with a 6-term correction, without relying on the gamma function. Parameters: - `x` (double): value to approximate the factorial of; accuracy improves for larger `x` (already near double-precision-level accuracy for `x >= 5`). Returns the approximate result as a double. See also [[factorial]], [[log-stirling-factorial]].
(sum-of-products a b c d)Computes a*b + c*d using Kahan's two-product algorithm to avoid catastrophic cancellation when a*b and c*d have opposite signs and are close in magnitude.
Parameters:
a, b, c, d (doubles): factors of the two products.Returns a*b + c*d as a double, computed via two fused multiply-adds rather than a direct sum of two separately-rounded products. This achieves near full double precision even when the naive (+ (* a b) (* c d)) loses many significant digits to cancellation. Requires a true hardware/JVM fused multiply-add (Java 9+) to realize the accuracy benefit; on earlier JVMs it is numerically equivalent to the naive computation.
See also difference-of-products, fma.
Computes `a*b + c*d` using Kahan's two-product algorithm to avoid catastrophic cancellation when `a*b` and `c*d` have opposite signs and are close in magnitude. Parameters: - `a`, `b`, `c`, `d` (doubles): factors of the two products. Returns `a*b + c*d` as a double, computed via two fused multiply-adds rather than a direct sum of two separately-rounded products. This achieves near full double precision even when the naive `(+ (* a b) (* c d))` loses many significant digits to cancellation. Requires a true hardware/JVM fused multiply-add (Java 9+) to realize the accuracy benefit; on earlier JVMs it is numerically equivalent to the naive computation. See also [[difference-of-products]], [[fma]].
(tanpi x)Computes tan(π·x) -- the tangent of x expressed in half-turns (units of π) rather than radians.
Parameters:
x (double): value in half-turns to take the tangent of.Returns tan(π·x) as a double, accurate to about 1 ulp for any x (the argument is reduced exactly). The signs follow the quotient of sinpi and cospi: at an integer x the result is a signed zero, at a half-integer x it is ##Inf or ##-Inf. Infinite or NaN x gives ##NaN.
Computes `tan(π·x)` -- the tangent of `x` expressed in half-turns (units of π) rather than radians. Parameters: - `x` (double): value in half-turns to take the tangent of. Returns `tan(π·x)` as a double, accurate to about 1 ulp for any `x` (the argument is reduced exactly). The signs follow the quotient of [[sinpi]] and [[cospi]]: at an integer `x` the result is a signed zero, at a half-integer `x` it is `##Inf` or `##-Inf`. Infinite or NaN `x` gives `##NaN`. See also [[tan]], [[sinpi]], [[cospi]], [[cotpi]].
(tpow x exponent)(tpow x exponent shift)Calculates the truncated power function of x.
This is the truncated power basis function commonly used to construct splines, defined as (x-shift)^exponent when x is greater than shift, and 0.0 otherwise.
Parameters:
x (double): Input value.exponent (double): Power to raise (x-shift) to.shift (double): Truncation point. Defaults to 0.0.Returns (x-shift)^exponent as a double when x > shift, 0.0 when x <= shift.
Calculates the truncated power function of `x`. This is the truncated power basis function commonly used to construct splines, defined as `(x-shift)^exponent` when `x` is greater than `shift`, and `0.0` otherwise. Parameters: - `x` (double): Input value. - `exponent` (double): Power to raise `(x-shift)` to. - `shift` (double): Truncation point. Defaults to `0.0`. Returns `(x-shift)^exponent` as a double when `x > shift`, `0.0` when `x <= shift`.
(trunc v)Truncates the fractional part of v, rounding towards zero.
Parameters:
v (double): the number to truncate.Returns the integer part of v as a double, preserving sign: ceil for negative v, floor otherwise.
See also itrunc.
Truncates the fractional part of `v`, rounding towards zero. Parameters: - `v` (double): the number to truncate. Returns the integer part of `v` as a double, preserving sign: [[ceil]] for negative `v`, [[floor]] otherwise. See also [[itrunc]].
(ulp x)Unit in the Last Place, distance between next value larger than x and x
Unit in the Last Place, distance between next value larger than `x` and `x`
(unsigned-bit-shift-right x shift)Shift bits right and set most significant bit to 0
Shift bits right and set most significant bit to `0`
(unuse-primitive-operators)(unuse-primitive-operators skip-set)Undoes the work of use-primitive-operators. This is idempotent.
Undoes the work of [[use-primitive-operators]]. This is idempotent.
(use-primitive-operators)(use-primitive-operators skip-set)Replaces Clojure's arithmetic and number coercion functions with primitive equivalents. These are
defined as macros, so they cannot be used as higher-order functions. This is an idempotent operation. Undo with unuse-primitive-operators.
Replaces Clojure's arithmetic and number coercion functions with primitive equivalents. These are defined as macros, so they cannot be used as higher-order functions. This is an idempotent operation. Undo with [[unuse-primitive-operators]].
(valid-double? v)Check if a number is finite double.
Check if a number is finite double.
(vercos x)Computes the vercosine (versed cosine) of x, vercos(x) = 1 + cos(x).
Parameters:
x (double): angle in radians.Returns the vercosine as a double, always in [0, 2].
Computes the vercosine (versed cosine) of `x`, `vercos(x) = 1 + cos(x)`. Parameters: - `x` (double): angle in radians. Returns the vercosine as a double, always in `[0, 2]`. See also [[avercos]], [[versin]], [[covercos]].
(versin x)Computes the versine (versed sine) of x, versin(x) = 1 - cos(x).
Parameters:
x (double): angle in radians.Returns the versine as a double, always in [0, 2].
Computes the versine (versed sine) of `x`, `versin(x) = 1 - cos(x)`. Parameters: - `x` (double): angle in radians. Returns the versine as a double, always in `[0, 2]`. See also [[aversin]], [[coversin]], [[vercos]], [[haversin]].
(wrap [start stop] value)(wrap start stop value)Wraps value cyclically into the range [start,stop), similar to openFrameworks' ofWrap.
When value lies outside the range, it is shifted by an integer multiple of the range width until it falls back inside, effectively behaving like a floating-point modulo operation over the range. This is useful for wrapping angles, cyclic coordinates, or any periodic quantity. start and stop do not need to be ordered, the range is normalized internally.
Parameters:
[start stop] (sequence of two doubles), value (double): Range provided as a pair, plus the value to wrap.start, stop, value (doubles): Range boundaries and the value to wrap, given directly.Returns the wrapped value as a double, always within [start,stop). Returns stop when start equals stop.
Wraps `value` cyclically into the range `[start,stop)`, similar to `openFrameworks`' `ofWrap`. When `value` lies outside the range, it is shifted by an integer multiple of the range width until it falls back inside, effectively behaving like a floating-point modulo operation over the range. This is useful for wrapping angles, cyclic coordinates, or any periodic quantity. `start` and `stop` do not need to be ordered, the range is normalized internally. Parameters: - `[start stop]` (sequence of two doubles), `value` (double): Range provided as a pair, plus the value to wrap. - `start`, `stop`, `value` (doubles): Range boundaries and the value to wrap, given directly. Returns the wrapped value as a double, always within `[start,stop)`. Returns `stop` when `start` equals `stop`. See also [[constrain]] (clamping instead of wrapping), [[norm]].
(xexpx x)Computes x * exp(x), with the convention that the result is 0.0 whenever exp(x) underflows to zero (rather than propagating a spurious 0.0 * x).
Parameters:
x (double): value.Returns the result as a double.
See also xexpy.
Computes `x * exp(x)`, with the convention that the result is `0.0` whenever `exp(x)` underflows to zero (rather than propagating a spurious `0.0 * x`). Parameters: - `x` (double): value. Returns the result as a double. See also [[xexpy]].
(xexpy x y)Computes x * exp(y), with the convention that the result is 0.0 whenever exp(y) underflows to zero and x is not ##NaN.
Parameters:
x, y (doubles): values.Returns the result as a double.
See also xexpx.
Computes `x * exp(y)`, with the convention that the result is `0.0` whenever `exp(y)` underflows to zero and `x` is not `##NaN`. Parameters: - `x`, `y` (doubles): values. Returns the result as a double. See also [[xexpx]].
(xlog1py x y)Computes x * log(1+y), with the convention 0 * log1p(y) = 0 (rather than ##NaN) whenever x is zero and y is not ##NaN.
Parameters:
x, y (doubles): values; y must be greater than -1 for a real result.Returns the result as a double.
Computes `x * log(1+y)`, with the convention `0 * log1p(y) = 0` (rather than `##NaN`) whenever `x` is zero and `y` is not `##NaN`. Parameters: - `x`, `y` (doubles): values; `y` must be greater than `-1` for a real result. Returns the result as a double. See also [[xlogy]], [[log1p]].
(xlogx x)Computes x * log(x), with the convention 0 * log(0) = 0 (the limiting value, rather than ##NaN).
Parameters:
x (double): value; must be non-negative for a real result.Returns the result as a double.
See also xlogy.
Computes `x * log(x)`, with the convention `0 * log(0) = 0` (the limiting value, rather than `##NaN`). Parameters: - `x` (double): value; must be non-negative for a real result. Returns the result as a double. See also [[xlogy]].
(xlogy x y)Computes x * log(y), with the convention 0 * log(y) = 0 (rather than ##NaN) whenever x is zero and y is not ##NaN.
Parameters:
x, y (doubles): values; y must be non-negative for a real result.Returns the result as a double.
Computes `x * log(y)`, with the convention `0 * log(y) = 0` (rather than `##NaN`) whenever `x` is zero and `y` is not `##NaN`. Parameters: - `x`, `y` (doubles): values; `y` must be non-negative for a real result. Returns the result as a double. See also [[xlogx]], [[xlog1py]].
(xor x y)(xor x y & r)Primitive boolean XOR of two or more values. Identical implementation to bool-xor.
Parameters:
Returns the exclusive-or of all arguments as a Boolean, computed by folding pairwise from left to right (associative, so fold order does not affect the result).
Primitive boolean XOR of two or more values. Identical implementation to [[bool-xor]]. Parameters: - two or more values (coerced to boolean). Returns the exclusive-or of all arguments as a Boolean, computed by folding pairwise from left to right (associative, so fold order does not affect the result). See also [[bool-xor]], [[bool-not]].
cljdoc builds & hosts documentation for Clojure/Script libraries
| Ctrl+k | Jump to recent docs |
| ← | Move to previous article |
| → | Move to next article |
| Ctrl+/ | Jump to the search field |