Vector types and vector algebra operations.
Provides vector operations inspired by libraries like Processing and openFrameworks. Supported representations include fixed-size custom types Vec2 (2d), Vec3 (3d), Vec4 (4d) and ArrayVec (n-dimensional wrapper around double[]); double arrays; variable-size Clojure collections (persistent vectors and sequences); and plain numbers, treated as 1d vectors. Most operations are defined through the VectorProto protocol, extended for all supported types; the vector types also implement standard Clojure/Java protocols (Seqable, Indexed, IFn, Counted, Associative, IReduce, ILookup, and others), so they can be used as sequences, arrays or functions.
Constructors build vectors from components, sequences or arrays: vec2, vec3, vec4, array-vec, make-vector, real-vector, array->vec2, array->vec3, array->vec4, seq->vec2, seq->vec3, seq->vec4, and random vectors with generate-vec2, generate-vec3, generate-vec4. Conversion helpers move between representations: vec->array, vec->seq, vec->vector, vec->RealVector, vec->Vec, as-vec.
Basic properties and predicates are provided by size, fmap, magsq, mag, sum, prod, mx, mn, emx, emn, maxdim, mindim, approx, delta-eq, edelta-eq, zero?, is-zero?, near-zero?, is-near-zero?, zero-count and nonzero-count.
Elementwise and scalar arithmetic includes add, sub, shift, mult, emult, div, ediv, abs, reciprocal, permute, interpolate, lerp, einterpolate, econstrain and clamp.
Geometric operations include dot, cross, triple-product, heading, rotate, axis-rotate, perpendicular, transform, to-polar, from-polar, project, faceforward, angle-between, relative-angle-between, aligned?, normalize (and its normalize-L1, normalize-L2, normalize-L2sq, normalize-LInf variants), set-mag and limit.
Distance and similarity functions include dist, dist-sq, dist-abs, dist-cheb, dist-discrete, dist-canberra, dist-emd, dist-ang, sim-cos and distance.
Aggregate and statistical helpers include average, average-vectors, differences, unwrap, pow, softmax, logsoftmax, logsumexp and logmeanexp.
Orthogonal and orthonormal polynomial bases over a sequence of values are built with orthogonal-polynomials and orthonormal-polynomials.
Vector types and vector algebra operations. Provides vector operations inspired by libraries like Processing and openFrameworks. Supported representations include fixed-size custom types `Vec2` (2d), `Vec3` (3d), `Vec4` (4d) and `ArrayVec` (n-dimensional wrapper around `double[]`); `double` arrays; variable-size Clojure collections (persistent vectors and sequences); and plain numbers, treated as 1d vectors. Most operations are defined through the `VectorProto` protocol, extended for all supported types; the vector types also implement standard Clojure/Java protocols (`Seqable`, `Indexed`, `IFn`, `Counted`, `Associative`, `IReduce`, `ILookup`, and others), so they can be used as sequences, arrays or functions. Constructors build vectors from components, sequences or arrays: `vec2`, `vec3`, `vec4`, `array-vec`, `make-vector`, `real-vector`, `array->vec2`, `array->vec3`, `array->vec4`, `seq->vec2`, `seq->vec3`, `seq->vec4`, and random vectors with `generate-vec2`, `generate-vec3`, `generate-vec4`. Conversion helpers move between representations: `vec->array`, `vec->seq`, `vec->vector`, `vec->RealVector`, `vec->Vec`, `as-vec`. Basic properties and predicates are provided by `size`, `fmap`, `magsq`, `mag`, `sum`, `prod`, `mx`, `mn`, `emx`, `emn`, `maxdim`, `mindim`, `approx`, `delta-eq`, `edelta-eq`, `zero?`, `is-zero?`, `near-zero?`, `is-near-zero?`, `zero-count` and `nonzero-count`. Elementwise and scalar arithmetic includes `add`, `sub`, `shift`, `mult`, `emult`, `div`, `ediv`, `abs`, `reciprocal`, `permute`, `interpolate`, `lerp`, `einterpolate`, `econstrain` and `clamp`. Geometric operations include `dot`, `cross`, `triple-product`, `heading`, `rotate`, `axis-rotate`, `perpendicular`, `transform`, `to-polar`, `from-polar`, `project`, `faceforward`, `angle-between`, `relative-angle-between`, `aligned?`, `normalize` (and its `normalize-L1`, `normalize-L2`, `normalize-L2sq`, `normalize-LInf` variants), `set-mag` and `limit`. Distance and similarity functions include `dist`, `dist-sq`, `dist-abs`, `dist-cheb`, `dist-discrete`, `dist-canberra`, `dist-emd`, `dist-ang`, `sim-cos` and `distance`. Aggregate and statistical helpers include `average`, `average-vectors`, `differences`, `unwrap`, `pow`, `softmax`, `logsoftmax`, `logsumexp` and `logmeanexp`. Orthogonal and orthonormal polynomial bases over a sequence of values are built with `orthogonal-polynomials` and `orthonormal-polynomials`.
(acos vector)Applies fastmath.core/acos to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/acos]] to every element of `v`, elementwise, returning a vector of the same type.
(acosh vector)Applies fastmath.core/acosh to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/acosh]] to every element of `v`, elementwise, returning a vector of the same type.
(acot vector)Applies fastmath.core/acot to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/acot]] to every element of `v`, elementwise, returning a vector of the same type.
(acoth vector)Applies fastmath.core/acoth to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/acoth]] to every element of `v`, elementwise, returning a vector of the same type.
(acsc vector)Applies fastmath.core/acsc to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/acsc]] to every element of `v`, elementwise, returning a vector of the same type.
(acsch vector)Applies fastmath.core/acsch to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/acsch]] to every element of `v`, elementwise, returning a vector of the same type.
(add v)(add v1 v2)Sum of two vectors, elementwise.
With one argument, returns v unchanged. When v1 and v2 are variable-length sequences of different lengths, the result is truncated to the shorter length.
Sum of two vectors, elementwise. With one argument, returns `v` unchanged. When `v1` and `v2` are variable-length sequences of different lengths, the result is truncated to the shorter length.
(aligned? v1 v2)(aligned? v1 v2 tol)Checks if two vectors are aligned, meaning they point in approximately the same direction.
This is determined by checking if the angle between them (calculated using angle-between)
is less than the specified tolerance.
Defaults to an absolute tolerance of 1.0e-6.
Checks if two vectors are aligned, meaning they point in approximately the same direction. This is determined by checking if the angle between them (calculated using [[angle-between]]) is less than the specified `tolerance`. Defaults to an absolute tolerance of `1.0e-6`.
(angle-between v1 v2)Returns the angle between two vectors in radians.
The angle is always positive and lies between 0 and π. Returns 0 if either vector is zero.
Returns the angle between two vectors in radians. The angle is always positive and lies between 0 and π. Returns 0 if either vector is zero.
(approx v)(approx v d)Rounds every element of v to d (default: 2) decimal places, returning a vector of the same type and dimension.
Rounds every element of `v` to `d` (default: 2) decimal places, returning a vector of the same type and dimension.
(array->vec2 arr)Converts a double array to a Vec2, reading its first two elements as x and y.
Throws ArrayIndexOutOfBoundsException if arr has fewer than 2 elements; extra elements are ignored.
See also array->vec3, array->vec4, seq->vec2.
Converts a `double` array to a `Vec2`, reading its first two elements as `x` and `y`. Throws `ArrayIndexOutOfBoundsException` if `arr` has fewer than 2 elements; extra elements are ignored. See also [[array->vec3]], [[array->vec4]], [[seq->vec2]].
(array->vec3 arr)Converts a double array to a Vec3, reading its first three elements as x, y and z.
Throws ArrayIndexOutOfBoundsException if arr has fewer than 3 elements; extra elements are ignored.
See also array->vec2, array->vec4, seq->vec3.
Converts a `double` array to a `Vec3`, reading its first three elements as `x`, `y` and `z`. Throws `ArrayIndexOutOfBoundsException` if `arr` has fewer than 3 elements; extra elements are ignored. See also [[array->vec2]], [[array->vec4]], [[seq->vec3]].
(array->vec4 arr)Converts a double array to a Vec4, reading its first four elements as x, y, z and w.
Throws ArrayIndexOutOfBoundsException if arr has fewer than 4 elements; extra elements are ignored.
See also array->vec2, array->vec3, seq->vec4.
Converts a `double` array to a `Vec4`, reading its first four elements as `x`, `y`, `z` and `w`. Throws `ArrayIndexOutOfBoundsException` if `arr` has fewer than 4 elements; extra elements are ignored. See also [[array->vec2]], [[array->vec3]], [[seq->vec4]].
(array-vec xs)Creates ArrayVec type based on provided sequence xs.
Creates ArrayVec type based on provided sequence `xs`.
(as-vec v)(as-vec v xs)Creates a vector of the same type and dimension as v, filled from a sequence xs.
Parameters:
v: a vector whose type and size determine the shape of the result.xs (optional): values to fill in, taken in order; missing values default to 0.0, extra values are ignored. When omitted, returns the zero vector of v's type and size.Used internally by normalize and its variants to produce a zero vector when the input vector's magnitude is zero.
Creates a vector of the same type and dimension as `v`, filled from a sequence `xs`. Parameters: - `v`: a vector whose type and size determine the shape of the result. - `xs` (optional): values to fill in, taken in order; missing values default to `0.0`, extra values are ignored. When omitted, returns the zero vector of `v`'s type and size. Used internally by [[normalize]] and its variants to produce a zero vector when the input vector's magnitude is zero.
(asec vector)Applies fastmath.core/asec to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/asec]] to every element of `v`, elementwise, returning a vector of the same type.
(asech vector)Applies fastmath.core/asech to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/asech]] to every element of `v`, elementwise, returning a vector of the same type.
(asin vector)Applies fastmath.core/asin to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/asin]] to every element of `v`, elementwise, returning a vector of the same type.
(asinh vector)Applies fastmath.core/asinh to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/asinh]] to every element of `v`, elementwise, returning a vector of the same type.
(atan vector)Applies fastmath.core/atan to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/atan]] to every element of `v`, elementwise, returning a vector of the same type.
(atanh vector)Applies fastmath.core/atanh to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/atanh]] to every element of `v`, elementwise, returning a vector of the same type.
(average v)(average v weights)Computes the mean, or weighted mean, of the elements of v.
Parameters:
[v]: unweighted arithmetic mean, sum(v) / size(v).[v weights]: weighted mean, dot(v, weights) / sum(weights).See also average-vectors (average across multiple vectors, not within one).
Computes the mean, or weighted mean, of the elements of `v`. Parameters: - `[v]`: unweighted arithmetic mean, `sum(v) / size(v)`. - `[v weights]`: weighted mean, `dot(v, weights) / sum(weights)`. See also [[average-vectors]] (average across multiple vectors, not within one).
(average-vectors vs)(average-vectors init vs)Computes the average (centroid) of a collection of vectors.
Parameters:
[vs]: averages all vectors in vs.[init vs]: averages init together with all vectors in vs (init counts as one additional vector, not a separate running accumulator); the result is divided by (inc (count vs)), the total number of vectors including init.See also average (mean of a single vector's own elements, not across multiple vectors).
Computes the average (centroid) of a collection of vectors. Parameters: - `[vs]`: averages all vectors in `vs`. - `[init vs]`: averages `init` together with all vectors in `vs` (`init` counts as one additional vector, not a separate running accumulator); the result is divided by `(inc (count vs))`, the total number of vectors including `init`. See also [[average]] (mean of a single vector's own elements, not across multiple vectors).
(axis-rotate v angle axis)(axis-rotate v angle axis pivot)Rotates a Vec3 by angle radians around an arbitrary axis, following the right-hand rule (axis need not be normalized).
Parameters:
[v angle axis]: rotates v around axis through the origin.[v angle axis pivot]: rotates v around an axis parallel to axis passing through pivot; equivalent to translating v by -pivot, rotating, then translating back.Only implemented for Vec3.
See also rotate (fixed-axis Euler rotation).
Rotates a `Vec3` by `angle` radians around an arbitrary `axis`, following the right-hand rule (`axis` need not be normalized). Parameters: - `[v angle axis]`: rotates `v` around `axis` through the origin. - `[v angle axis pivot]`: rotates `v` around an axis parallel to `axis` passing through `pivot`; equivalent to translating `v` by `-pivot`, rotating, then translating back. Only implemented for `Vec3`. See also [[rotate]] (fixed-axis Euler rotation).
(base-from v)Returns a list of mutually perpendicular vectors derived from v, forming an orthogonal basis.
The first element is v itself, unchanged (not normalized). The remaining elements are unit vectors: for Vec2, a single unit vector perpendicular to v (see perpendicular); for Vec3, a unit vector perpendicular to v, followed by their cross product (which has the same magnitude as v, since the second element is a unit vector).
Only implemented for Vec2 and Vec3.
Returns a list of mutually perpendicular vectors derived from `v`, forming an orthogonal basis. The first element is `v` itself, unchanged (not normalized). The remaining elements are unit vectors: for `Vec2`, a single unit vector perpendicular to `v` (see [[perpendicular]]); for `Vec3`, a unit vector perpendicular to `v`, followed by their [[cross]] product (which has the same magnitude as `v`, since the second element is a unit vector). Only implemented for `Vec2` and `Vec3`.
(cb vector)Applies fastmath.core/cb to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/cb]] to every element of `v`, elementwise, returning a vector of the same type.
(cbrt vector)Applies fastmath.core/cbrt to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/cbrt]] to every element of `v`, elementwise, returning a vector of the same type.
(ceil vector)Applies fastmath.core/ceil to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/ceil]] to every element of `v`, elementwise, returning a vector of the same type.
(clamp v)(clamp v mn mx)Clamps the elements of vector v element-wise between a minimum (mn) and maximum (mx) value.
In the single-arity version [v], elements are clamped between 0.0 and Double/MAX_VALUE.
Clamps the elements of vector `v` element-wise between a minimum (`mn`) and maximum (`mx`) value. In the single-arity version `[v]`, elements are clamped between 0.0 and `Double/MAX_VALUE`.
(cos vector)Applies fastmath.core/cos to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/cos]] to every element of `v`, elementwise, returning a vector of the same type.
(cosh vector)Applies fastmath.core/cosh to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/cosh]] to every element of `v`, elementwise, returning a vector of the same type.
(cot vector)Applies fastmath.core/cot to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/cot]] to every element of `v`, elementwise, returning a vector of the same type.
(coth vector)Applies fastmath.core/coth to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/coth]] to every element of `v`, elementwise, returning a vector of the same type.
(cross v1 v2)Cross product of two vectors.
For Vec2, returns a scalar: the signed magnitude of the cross product (equivalently, the z-component if both vectors were embedded in the xy-plane of 3d space), positive when v2 is counter-clockwise from v1.
For Vec3, returns a Vec3 perpendicular to both v1 and v2, following the right-hand rule, with magnitude equal to mag(v1) * mag(v2) * sin(angle-between v1 v2).
Not implemented for Vec4 or other representations.
See also triple-product.
Cross product of two vectors. For `Vec2`, returns a scalar: the signed magnitude of the cross product (equivalently, the z-component if both vectors were embedded in the xy-plane of 3d space), positive when `v2` is counter-clockwise from `v1`. For `Vec3`, returns a `Vec3` perpendicular to both `v1` and `v2`, following the right-hand rule, with magnitude equal to `mag(v1) * mag(v2) * sin(angle-between v1 v2)`. Not implemented for `Vec4` or other representations. See also [[triple-product]].
(csc vector)Applies fastmath.core/csc to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/csc]] to every element of `v`, elementwise, returning a vector of the same type.
(csch vector)Applies fastmath.core/csch to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/csch]] to every element of `v`, elementwise, returning a vector of the same type.
(degrees vector)Applies fastmath.core/degrees to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/degrees]] to every element of `v`, elementwise, returning a vector of the same type.
(delta-eq v1 v2)(delta-eq v1 v2 abs-tol)(delta-eq v1 v2 abs-tol rel-tol)Equality with given absolute (and/or relative) tolerance. Default 1.0e-6 absolute tolerance.
Vectors of different lengths are never equal: sub's elementwise subtraction silently
truncates to the shorter length (e.g. via map), so without this check a vector would
compare equal to any prefix of itself, and any vector would compare equal to an empty one.
With a relative tolerance (rel-tol), the combined tolerance is max(abs-tol, rel-tol * max(mag(v1), mag(v2))), mirroring fastmath.core/delta-eq's scalar convention.
Equality with given absolute (and/or relative) tolerance. Default 1.0e-6 absolute tolerance. Vectors of different lengths are never equal: `sub`'s elementwise subtraction silently truncates to the shorter length (e.g. via `map`), so without this check a vector would compare equal to any prefix of itself, and any vector would compare equal to an empty one. With a relative tolerance (`rel-tol`), the combined tolerance is `max(abs-tol, rel-tol * max(mag(v1), mag(v2)))`, mirroring [[fastmath.core/delta-eq]]'s scalar convention.
(dhash-code a)(dhash-code state a)Computes a hash code for a double value, based on its IEEE 754 bit pattern.
Parameters:
[a]: hash of a single value, combined with a fixed seed.[state a]: folds a into a running state, for combining the hashes of multiple values in sequence (e.g. all components of a vector).Since the hash is derived from the raw bit pattern, 0.0 and -0.0 (which are == to each other) hash to different values, matching java.lang.Double/hashCode's own convention.
Backs the hashCode/hasheq implementations of Vec2, Vec3, Vec4 and ArrayVec.
Computes a hash code for a `double` value, based on its IEEE 754 bit pattern. Parameters: - `[a]`: hash of a single value, combined with a fixed seed. - `[state a]`: folds `a` into a running `state`, for combining the hashes of multiple values in sequence (e.g. all components of a vector). Since the hash is derived from the raw bit pattern, `0.0` and `-0.0` (which are `==` to each other) hash to different values, matching `java.lang.Double/hashCode`'s own convention. Backs the `hashCode`/`hasheq` implementations of `Vec2`, `Vec3`, `Vec4` and `ArrayVec`.
(differences v)(differences v diffs)(differences v diffs lag)Computes the lagged differences of a vector or sequence.
This function calculates the difference between elements separated by a fixed distance (lag)
and can apply this operation diffs times.
It supports multiple arities:
[v]: Computes the 1st difference with lag 1 (default: diffs=1, lag=1).[v diffs]: Computes the diffs-th difference with lag 1 (default: lag=1).[v diffs lag]: Computes the diffs-th difference with the specified lag.Returns a sequence of the computed differences.
Computes the lagged differences of a vector or sequence. This function calculates the difference between elements separated by a fixed distance (`lag`) and can apply this operation `diffs` times. It supports multiple arities: - `[v]`: Computes the 1st difference with lag 1 (default: `diffs=1`, `lag=1`). - `[v diffs]`: Computes the `diffs`-th difference with lag 1 (default: `lag=1`). - `[v diffs lag]`: Computes the `diffs`-th difference with the specified `lag`. Returns a sequence of the computed differences.
(dist v1 v2)Euclidean distance between vectors
Euclidean distance between vectors
(dist-abs v1 v2)Manhattan distance between vectors
Manhattan distance between vectors
(dist-ang v1 v2)Angular distance: the angle between v1 and v2 (see angle-between), scaled to [0,1] by dividing by π.
Angular distance: the angle between `v1` and `v2` (see [[angle-between]]), scaled to `[0,1]` by dividing by π.
(dist-canberra v1 v2)Canberra distance: the sum, over each element pair, of |x1-x2| / (|x1|+|x2|).
A pair where both elements are 0.0 contributes 0.0 to the sum rather than 0.0/0.0 (##NaN).
Canberra distance: the sum, over each element pair, of `|x1-x2| / (|x1|+|x2|)`. A pair where both elements are `0.0` contributes `0.0` to the sum rather than `0.0/0.0` (`##NaN`).
(dist-cheb v1 v2)Chebyshev distance between vectors: the maximum absolute elementwise difference.
Chebyshev distance between vectors: the maximum absolute elementwise difference.
(dist-discrete v1 v2)(dist-discrete v1 v2 eps)Computes the discrete distance between two vectors v1 and v2.
This is the number of positions where the corresponding elements are considered different.
With an optional absolute tolerance eps, elements at index i are considered different if |v1_i - v2_i| > eps.
Returns the count of differing elements.
Computes the discrete distance between two vectors `v1` and `v2`. This is the number of positions where the corresponding elements are considered different. With an optional absolute tolerance `eps`, elements at index `i` are considered different if `|v1_i - v2_i| > eps`. Returns the count of differing elements.
(dist-emd v1 v2)Earth Mover's Distance (1d, exact): the minimal total amount of pairwise-index-wise value that must be moved between corresponding elements of v1 and v2 to turn one into the other.
Assumes v1 and v2 are sequences of the same length representing values over the same ordered set of positions (e.g. histogram bins).
Earth Mover's Distance (1d, exact): the minimal total amount of pairwise-index-wise value that must be moved between corresponding elements of `v1` and `v2` to turn one into the other. Assumes `v1` and `v2` are sequences of the same length representing values over the same ordered set of positions (e.g. histogram bins).
(dist-sq v1 v2)Squared Euclidean distance between vectors
Squared Euclidean distance between vectors
(distance v1 v2)(distance distance-method v1 v2)Distance between two vectors, dispatched by a named method (default: :euclidean).
See distances for the full list of available distance-method keywords.
Distance between two vectors, dispatched by a named method (default: `:euclidean`). See [[distances]] for the full list of available `distance-method` keywords.
Map of available named distance functions, keyed by the keyword accepted by distance: :euclidean/:euclide and :euclidean-sq/:euclid-sq (aliases for dist/dist-sq), :abs (dist-abs), :cheb/:chebyshev (dist-cheb), :canberra (dist-canberra), :emd (dist-emd), :angular (dist-ang), :discrete (dist-discrete).
Map of available named distance functions, keyed by the keyword accepted by [[distance]]: `:euclidean`/`:euclide` and `:euclidean-sq`/`:euclid-sq` (aliases for [[dist]]/[[dist-sq]]), `:abs` ([[dist-abs]]), `:cheb`/`:chebyshev` ([[dist-cheb]]), `:canberra` ([[dist-canberra]]), `:emd` ([[dist-emd]]), `:angular` ([[dist-ang]]), `:discrete` ([[dist-discrete]]).
(div v1)(div v1 v)Vector division by a number or the reciprocal of a vector.
The vector is multiplied by 1/v. When 1/v is not an accurate number, it overflows (v below 5.6e-309) or it is subnormal (v above 4.5e307), every element is divided by v instead, so the result is correct for the whole range of doubles.
Vector division by a number or the reciprocal of a vector. The vector is multiplied by `1/v`. When `1/v` is not an accurate number, it overflows (`v` below 5.6e-309) or it is subnormal (`v` above 4.5e307), every element is divided by `v` instead, so the result is correct for the whole range of doubles.
(dot v1 v2)Dot product of two vectors: the sum of the elementwise products.
Equal to magsq when both arguments are the same vector.
Dot product of two vectors: the sum of the elementwise products. Equal to [[magsq]] when both arguments are the same vector.
(econstrain v mn mx)Clamps every element of v to the closed interval [mn, mx], returning a vector of the same type and dimension.
Clamps every element of `v` to the closed interval `[mn, mx]`, returning a vector of the same type and dimension.
(edelta-eq v1 v2)(edelta-eq v1 v2 abs-tol)(edelta-eq v1 v2 abs-tol rel-tol)Element-wise equality with given absolute (and/or relative) toleance. Default 1.0e-6 absolute tolerance.
Element-wise equality with given absolute (and/or relative) toleance. Default 1.0e-6 absolute tolerance.
(ediv v1 v2)Element-wise division of two vectors.
Element-wise division of two vectors.
(einterpolate v1 v2 v)(einterpolate v1 v2 v f)Interpolates between two vectors, elementwise, with a separate interpolation parameter per element.
Parameters:
v1, v2: the vectors to interpolate between.v: a vector of per-element interpolation parameters, same dimension as v1/v2.f (optional, default fastmath.core/lerp): a function of (x1 x2 t) applied to each triple of corresponding elements.See also interpolate (single shared t).
Interpolates between two vectors, elementwise, with a separate interpolation parameter per element. Parameters: - `v1`, `v2`: the vectors to interpolate between. - `v`: a vector of per-element interpolation parameters, same dimension as `v1`/`v2`. - `f` (optional, default [[fastmath.core/lerp]]): a function of `(x1 x2 t)` applied to each triple of corresponding elements. See also [[interpolate]] (single shared `t`).
(emn v1 v2)Element-wise min from two vectors. When v1 and v2 are variable-length sequences of different lengths, the result is truncated to the shorter length.
Element-wise min from two vectors. When `v1` and `v2` are variable-length sequences of different lengths, the result is truncated to the shorter length.
(emult v1)(emult v1 v2)Element-wise vector multiplication (Hadamard product).
With one argument, returns v1 unchanged. When v1 and v2 are variable-length sequences of different lengths, the result is truncated to the shorter length.
Element-wise vector multiplication (Hadamard product). With one argument, returns `v1` unchanged. When `v1` and `v2` are variable-length sequences of different lengths, the result is truncated to the shorter length.
(emx v1 v2)Element-wise max from two vectors. When v1 and v2 are variable-length sequences of different lengths, the result is truncated to the shorter length.
Element-wise max from two vectors. When `v1` and `v2` are variable-length sequences of different lengths, the result is truncated to the shorter length.
(exp vector)Applies fastmath.core/exp to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/exp]] to every element of `v`, elementwise, returning a vector of the same type.
(expm1 vector)Applies fastmath.core/expm1 to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/expm1]] to every element of `v`, elementwise, returning a vector of the same type.
(faceforward n v)Flips vector n if dot(n, v) is negative. Returns n if dot(n, v) is non-negative. Useful for ensuring consistent vector orientation, such as making a normal vector face towards a reference vector v.
Flips vector `n` if `dot(n, v)` is negative. Returns `n` if `dot(n, v)` is non-negative. Useful for ensuring consistent vector orientation, such as making a normal vector face towards a reference vector `v`.
(floor vector)Applies fastmath.core/floor to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/floor]] to every element of `v`, elementwise, returning a vector of the same type.
(fmap v f)Applies a function f to every element of v, returning a new vector of the same type and dimension.
For a scalar (Number), f is applied once to the value itself. Unlike map, the result is never a lazy sequence.
See also approx (a common special case, rounding every element).
Applies a function `f` to every element of `v`, returning a new vector of the same type and dimension. For a scalar (`Number`), `f` is applied once to the value itself. Unlike `map`, the result is never a lazy sequence. See also [[approx]] (a common special case, rounding every element).
(frac vector)Applies fastmath.core/frac to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/frac]] to every element of `v`, elementwise, returning a vector of the same type.
(from-polar v)Converts v from polar (2d) or spherical (3d) coordinates back to Cartesian coordinates, using the same [r theta]/[r theta phi] convention as to-polar, which it inverts.
Only implemented for Vec2 and Vec3.
Converts `v` from polar (2d) or spherical (3d) coordinates back to Cartesian coordinates, using the same `[r theta]`/`[r theta phi]` convention as [[to-polar]], which it inverts. Only implemented for `Vec2` and `Vec3`.
(generate-vec2 f)(generate-vec2 f1 f2)Creates a Vec2 by evaluating no-argument functions for each component.
Parameters:
[f1 f2]: f1 is called for x, then f2 for y.[f]: f is called independently once per component (twice total); the two calls may return different values when f is not constant, e.g. a random number generator.See also generate-vec3, generate-vec4.
Creates a `Vec2` by evaluating no-argument functions for each component. Parameters: - `[f1 f2]`: `f1` is called for `x`, then `f2` for `y`. - `[f]`: `f` is called independently once per component (twice total); the two calls may return different values when `f` is not constant, e.g. a random number generator. See also [[generate-vec3]], [[generate-vec4]].
(generate-vec3 f)(generate-vec3 f1 f2 f3)Creates a Vec3 by evaluating no-argument functions for each component.
Parameters:
[f1 f2 f3]: f1 is called for x, then f2 for y, then f3 for z.[f]: f is called independently once per component (three times total); the calls may return different values when f is not constant, e.g. a random number generator.See also generate-vec2, generate-vec4.
Creates a `Vec3` by evaluating no-argument functions for each component. Parameters: - `[f1 f2 f3]`: `f1` is called for `x`, then `f2` for `y`, then `f3` for `z`. - `[f]`: `f` is called independently once per component (three times total); the calls may return different values when `f` is not constant, e.g. a random number generator. See also [[generate-vec2]], [[generate-vec4]].
(generate-vec4 f)(generate-vec4 f1 f2 f3 f4)Creates a Vec4 by evaluating no-argument functions for each component.
Parameters:
[f1 f2 f3 f4]: f1 is called for x, then f2 for y, then f3 for z, then f4 for w.[f]: f is called independently once per component (four times total); the calls may return different values when f is not constant, e.g. a random number generator.See also generate-vec2, generate-vec3.
Creates a `Vec4` by evaluating no-argument functions for each component. Parameters: - `[f1 f2 f3 f4]`: `f1` is called for `x`, then `f2` for `y`, then `f3` for `z`, then `f4` for `w`. - `[f]`: `f` is called independently once per component (four times total); the calls may return different values when `f` is not constant, e.g. a random number generator. See also [[generate-vec2]], [[generate-vec3]].
(heading v)Angle, in radians, between v and the primary axis unit vector [1,0,...].
For a 2d vector in any representation (Vec2, a two element sequence, a double array or RealVector of length 2), this is the signed polar angle atan2(y, x), ranging over the full circle from -π to π.
For every other dimension (Vec3, Vec4, longer sequences, double arrays, RealVector), this is the unsigned angle computed via angle-between against [1,0,...,0], ranging from 0 to π. Because that angle depends only on the dot product with the primary axis, it captures the vector's tilt away from that axis but not its full direction: for 3 or more dimensions it is degenerate, e.g. (heading [-1 4 0]) and (heading [-1 -4 0]) return the same value, since both vectors share the same x component and magnitude.
See also angle-between.
Angle, in radians, between `v` and the primary axis unit vector `[1,0,...]`. For a 2d vector in any representation (`Vec2`, a two element sequence, a `double` array or `RealVector` of length 2), this is the signed polar angle `atan2(y, x)`, ranging over the full circle from `-π` to `π`. For every other dimension (`Vec3`, `Vec4`, longer sequences, `double` arrays, `RealVector`), this is the unsigned angle computed via [[angle-between]] against `[1,0,...,0]`, ranging from `0` to `π`. Because that angle depends only on the dot product with the primary axis, it captures the vector's tilt away from that axis but not its full direction: for 3 or more dimensions it is degenerate, e.g. `(heading [-1 4 0])` and `(heading [-1 -4 0])` return the same value, since both vectors share the same `x` component and magnitude. See also [[angle-between]].
(interpolate v1 v2 t)(interpolate v1 v2 t f)Interpolates between two vectors, elementwise.
Parameters:
v1, v2: the vectors to interpolate between.t: interpolation parameter, typically in [0,1] (0 returns v1, 1 returns v2), though values outside this range are not rejected.f (optional, default fastmath.core/lerp): a function of (x1 x2 t) applied to each pair of corresponding elements.See also lerp, einterpolate (per-element t).
Interpolates between two vectors, elementwise. Parameters: - `v1`, `v2`: the vectors to interpolate between. - `t`: interpolation parameter, typically in `[0,1]` (`0` returns `v1`, `1` returns `v2`), though values outside this range are not rejected. - `f` (optional, default [[fastmath.core/lerp]]): a function of `(x1 x2 t)` applied to each pair of corresponding elements. See also [[lerp]], [[einterpolate]] (per-element `t`).
(is-near-zero? v)(is-near-zero? v abs-tol)(is-near-zero? v abs-tol rel-tol)Checks if mag of v is within the given absolute (and/or relative) tolerance of zero. Default 1.0e-6 absolute tolerance. Same as near-zero?.
Checks if [[mag]] of `v` is within the given absolute (and/or relative) tolerance of zero. Default 1.0e-6 absolute tolerance. Same as [[near-zero?]].
(is-zero? v)Checks if every element of v is exactly 0.0. Same as zero?.
Checks if every element of `v` is exactly `0.0`. Same as [[zero?]].
(lerp v1 v2 t)Linear interpolation of vectors. Same as interpolate with the default (lerp) interpolation function.
Linear interpolation of vectors. Same as [[interpolate]] with the default (`lerp`) interpolation function.
(limit v len)Caps the magnitude of v at len.
Returns v unchanged (the same value) if its magnitude is already <= len; otherwise returns set-mag applied with len.
Caps the magnitude of `v` at `len`. Returns `v` unchanged (the same value) if its magnitude is already `<= len`; otherwise returns [[set-mag]] applied with `len`.
(ln vector)Applies fastmath.core/ln to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/ln]] to every element of `v`, elementwise, returning a vector of the same type.
(log vector)Applies fastmath.core/log to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/log]] to every element of `v`, elementwise, returning a vector of the same type.
(log10 vector)Applies fastmath.core/log10 to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/log10]] to every element of `v`, elementwise, returning a vector of the same type.
(log1mexp vector)Applies fastmath.core/log1mexp to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/log1mexp]] to every element of `v`, elementwise, returning a vector of the same type.
(log1p vector)Applies fastmath.core/log1p to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/log1p]] to every element of `v`, elementwise, returning a vector of the same type.
(log1pexp vector)Applies fastmath.core/log1pexp to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/log1pexp]] to every element of `v`, elementwise, returning a vector of the same type.
(log1pmx vector)Applies fastmath.core/log1pmx to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/log1pmx]] to every element of `v`, elementwise, returning a vector of the same type.
(log1psq vector)Applies fastmath.core/log1psq to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/log1psq]] to every element of `v`, elementwise, returning a vector of the same type.
(log2 vector)Applies fastmath.core/log2 to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/log2]] to every element of `v`, elementwise, returning a vector of the same type.
(logexpm1 vector)Applies fastmath.core/logexpm1 to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/logexpm1]] to every element of `v`, elementwise, returning a vector of the same type.
(logit vector)Applies fastmath.core/logit to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/logit]] to every element of `v`, elementwise, returning a vector of the same type.
(logmeanexp v)Calculates the numerically stable log of the mean of the exponential of each element in vector v.
This is equivalent to log(mean(exp(v_i))) for all elements v_i in v.
It provides a numerically stable way to compute log(sum(exp(v_i))) - log(count(v)) by shifting values to prevent overflow during exponentiation.
Often used in machine learning and statistical contexts where dealing with large values inside exponentials is common.
Returns a double value: the maximum when it is infinite (##NaN if an element is ##NaN), ##NaN for an empty v (of any type).
Calculates the numerically stable log of the mean of the exponential of each element in vector `v`. This is equivalent to `log(mean(exp(v_i)))` for all elements `v_i` in `v`. It provides a numerically stable way to compute `log(sum(exp(v_i))) - log(count(v))` by shifting values to prevent overflow during exponentiation. Often used in machine learning and statistical contexts where dealing with large values inside exponentials is common. Returns a double value: the maximum when it is infinite (`##NaN` if an element is `##NaN`), `##NaN` for an empty `v` (of any type).
(logmxp1 vector)Applies fastmath.core/logmxp1 to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/logmxp1]] to every element of `v`, elementwise, returning a vector of the same type.
(logsoftmax v)(logsoftmax v t)Calculates the element-wise natural logarithm of the softmax function for the given vector v.
The standard log-softmax of an element v_i is log(softmax(v)_i), which is mathematically equivalent to v_i - log(sum_j(exp(v_j))).
This function provides a numerically stable implementation of this calculation, particularly useful for avoiding overflow and underflow issues when dealing with large or small exponential values.
It supports two arities:
[v]: Computes the standard log-softmax using the numerically stable form.[v t]: Computes the temperature-scaled log-softmax. Elements are divided by the temperature t before applying the log-softmax formula, i.e., v_i/t - log(sum_j(exp(v_j/t))). The temperature influences the shape of the corresponding softmax output distribution: t > 1 softens it, t < 1 sharpens it.Log-softmax is frequently used in numerical computations, especially in machine learning (e.g., as part of the cross-entropy loss function) for its superior numerical properties.
With infinite elements it returns the limit when one exists (0.0 at the single ##Inf element and ##-Inf elsewhere, [0.0] for a single element), ##NaN elements otherwise, as softmax.
Returns a new vector of the same type and dimension as the input.
Calculates the element-wise natural logarithm of the softmax function for the given vector `v`. The standard log-softmax of an element `v_i` is `log(softmax(v)_i)`, which is mathematically equivalent to `v_i - log(sum_j(exp(v_j)))`. This function provides a numerically stable implementation of this calculation, particularly useful for avoiding overflow and underflow issues when dealing with large or small exponential values. It supports two arities: - `[v]`: Computes the standard log-softmax using the numerically stable form. - `[v t]`: Computes the temperature-scaled log-softmax. Elements are divided by the temperature `t` *before* applying the log-softmax formula, i.e., `v_i/t - log(sum_j(exp(v_j/t)))`. The temperature influences the shape of the corresponding softmax output distribution: `t > 1` softens it, `t < 1` sharpens it. Log-softmax is frequently used in numerical computations, especially in machine learning (e.g., as part of the cross-entropy loss function) for its superior numerical properties. With infinite elements it returns the limit when one exists (`0.0` at the single `##Inf` element and `##-Inf` elsewhere, `[0.0]` for a single element), `##NaN` elements otherwise, as [[softmax]]. Returns a new vector of the same type and dimension as the input.
(logsumexp v)Calculates the LogSumExp of the vector v.
This is the numerically stable computation of log(sum(exp(x_i))) for all elements x_i in v.
It is often used to prevent overflow when exponentiating large numbers, especially in machine learning and statistics.
Returns a double value: the maximum when it is infinite (##NaN if an element is ##NaN), ##-Inf for an empty v (of any type).
Calculates the LogSumExp of the vector `v`. This is the numerically stable computation of `log(sum(exp(x_i)))` for all elements `x_i` in `v`. It is often used to prevent overflow when exponentiating large numbers, especially in machine learning and statistics. Returns a double value: the maximum when it is infinite (`##NaN` if an element is `##NaN`), `##-Inf` for an empty `v` (of any type).
(mag v)Returns the length (Euclidean norm) of the vector.
For Vec2, Vec3 and Vec4 the length is correct over the whole range of doubles (no overflow or underflow of the squares, for example 1e200 components).
Returns the length (Euclidean norm) of the vector. For `Vec2`, `Vec3` and `Vec4` the length is correct over the whole range of doubles (no overflow or underflow of the squares, for example `1e200` components).
(magsq v)Returns length of the vector squared.
Cheaper than mag since it avoids the square root; prefer it when only comparing magnitudes.
Returns length of the vector squared. Cheaper than [[mag]] since it avoids the square root; prefer it when only comparing magnitudes.
(make-vector dims)(make-vector dims xs)Creates a zero vector of the given number of dimensions, using the most specific available type.
Parameters:
Creates a zero vector of the given number of dimensions, using the most specific available type. Parameters: - `dims`: target dimension count. Returns `0.0` for `1`, [[vec2]], [[vec3]] or [[vec4]] for `2`, `3` or `4`, and a `double` array of zeros for `5` or more. Returns `nil` for `dims` less than `1`. - `xs` (optional): initial values, filled into the created vector via [[as-vec]] (extra values are dropped, missing values default to `0.0`).
(maxdim v)Index of the maximum value. On ties, returns the index of the first occurrence.
Index of the maximum value. On ties, returns the index of the first occurrence.
(mindim v)Index of the minimum value. On ties, returns the index of the first occurrence.
Index of the minimum value. On ties, returns the index of the first occurrence.
(mult v)(mult v x)Multiplies every element of v by number x.
With one argument, returns v unchanged.
Multiplies every element of `v` by number `x`. With one argument, returns `v` unchanged.
(near-zero? v)(near-zero? v abs-tol)(near-zero? v abs-tol rel-tol)Checks if mag of v is within the given absolute (and/or relative) tolerance of zero. Default 1.0e-6 absolute tolerance. Same as is-near-zero?.
Checks if [[mag]] of `v` is within the given absolute (and/or relative) tolerance of zero. Default 1.0e-6 absolute tolerance. Same as [[is-near-zero?]].
(nonzero-count v)Counts the number of elements of v not equal to 0.0.
See also zero-count.
Counts the number of elements of `v` not equal to `0.0`. See also [[zero-count]].
(normalize v)Returns a new vector of the same direction as v and magnitude of 1.
If v is a zero vector (magnitude is zero), returns a zero vector of the same type. A vector with finite elements is normalized also when its length is not representable (above the largest double, for example (1.7e308, 1.7e308)).
Returns a new vector of the same direction as `v` and magnitude of 1. If `v` is a zero vector (magnitude is zero), returns a zero vector of the same type. A vector with finite elements is normalized also when its length is not representable (above the largest double, for example `(1.7e308, 1.7e308)`).
(normalize-L1 v)Returns a new vector of the same direction as v, scaled so its L1 (sum-of-absolute-values) norm is 1.
If v is a zero vector (L1 norm is zero), returns a zero vector of the same type.
Returns a new vector of the same direction as `v`, scaled so its L1 (sum-of-absolute-values) norm is 1. If `v` is a zero vector (L1 norm is zero), returns a zero vector of the same type.
(normalize-L2sq v)Divides v by its squared L2 norm (magsq).
Unlike normalize/normalize-L1/normalize-LInf, the result does not have unit length: its magnitude is 1 / mag(v), not 1. Useful in formulas that call for dividing by the squared norm directly (e.g. vector reflection/inversion), rather than for producing a direction vector.
If v is a zero vector (magnitude is zero), returns a zero vector of the same type.
Divides `v` by its squared L2 norm ([[magsq]]). Unlike [[normalize]]/[[normalize-L1]]/[[normalize-LInf]], the result does not have unit length: its magnitude is `1 / mag(v)`, not `1`. Useful in formulas that call for dividing by the squared norm directly (e.g. vector reflection/inversion), rather than for producing a direction vector. If `v` is a zero vector (magnitude is zero), returns a zero vector of the same type.
(normalize-LInf v)Returns a new vector of the same direction as v, scaled so its L-infinity (maximum absolute element) norm is 1.
If v is a zero vector (L-infinity norm is zero), returns a zero vector of the same type.
Returns a new vector of the same direction as `v`, scaled so its L-infinity (maximum absolute element) norm is 1. If `v` is a zero vector (L-infinity norm is zero), returns a zero vector of the same type.
(orthogonal-polynomials xs)Generates a sequence of orthogonal vectors by evaluating orthogonal polynomials at the points specified in the input sequence xs.
The output vectors represent the values of orthogonal polynomials evaluated at the elements of xs. Orthogonality is defined with respect to the discrete inner product based on summation over the points in xs.
The sequence starts with the vector for the polynomial of degree 1 and includes vectors up to degree (count xs) - 1.
This function is useful for constructing orthogonal bases for polynomial approximation or regression on discrete data. The polynomials are monic, so their values grow fast with the degree and the number of points; use orthonormal-polynomials for more than about 20 points.
Generates a sequence of orthogonal vectors by evaluating orthogonal polynomials at the points specified in the input sequence `xs`. The output vectors represent the values of orthogonal polynomials evaluated at the elements of `xs`. Orthogonality is defined with respect to the discrete inner product based on summation over the points in `xs`. The sequence starts with the vector for the polynomial of degree 1 and includes vectors up to degree `(count xs) - 1`. This function is useful for constructing orthogonal bases for polynomial approximation or regression on discrete data. The polynomials are monic, so their values grow fast with the degree and the number of points; use [[orthonormal-polynomials]] for more than about 20 points.
(orthonormal-polynomials xs)Generates a sequence of orthonormal vectors by evaluating orthogonal polynomials at the points specified in the input sequence xs.
The sequence starts with the vector for the polynomial of degree 1 and includes vectors up to degree (count xs) - 1. Orthogonality (and thus orthonormality) is with respect to the discrete inner product based on summation over the points in xs. The vectors are the same as orthogonal-polynomials divided by their norms (the sign is the same: the leading coefficient is positive).
This function produces an orthonormal basis suitable for polynomial approximation or regression on discrete data points defined by xs (the columns of poly(xs, degree) of R). Each vector is the previous one multiplied by the centered points and orthogonalized against all previous vectors, so the vectors stay orthonormal also for a large number of points, where the values of orthogonal-polynomials grow too fast.
Returns a sequence of vectors, an empty one for fewer than two points. The points should be different: when some of them are repeated, there are fewer different polynomials than requested and the vectors of the higher degrees are filled with NaN.
Generates a sequence of orthonormal vectors by evaluating orthogonal polynomials at the points specified in the input sequence `xs`. The sequence starts with the vector for the polynomial of degree 1 and includes vectors up to degree `(count xs) - 1`. Orthogonality (and thus orthonormality) is with respect to the discrete inner product based on summation over the points in `xs`. The vectors are the same as [[orthogonal-polynomials]] divided by their norms (the sign is the same: the leading coefficient is positive). This function produces an orthonormal basis suitable for polynomial approximation or regression on discrete data points defined by `xs` (the columns of `poly(xs, degree)` of R). Each vector is the previous one multiplied by the centered points and orthogonalized against all previous vectors, so the vectors stay orthonormal also for a large number of points, where the values of [[orthogonal-polynomials]] grow too fast. Returns a sequence of vectors, an empty one for fewer than two points. The points should be different: when some of them are repeated, there are fewer different polynomials than requested and the vectors of the higher degrees are filled with `NaN`.
(permute v idxs)Permutes vector elements with given indices idxs, i.e. returns a vector where element i is (v (idxs i)).
Indices may repeat or be omitted (the result has the same dimension as idxs, not v).
Not implemented for Number, double arrays, RealVector or ArrayVec (no reordering applies to a scalar, and those representations don't support it).
Permutes vector elements with given indices `idxs`, i.e. returns a vector where element `i` is `(v (idxs i))`. Indices may repeat or be omitted (the result has the same dimension as `idxs`, not `v`). Not implemented for `Number`, `double` arrays, `RealVector` or `ArrayVec` (no reordering applies to a scalar, and those representations don't support it).
(perpendicular v)(perpendicular v1 v2)Returns a unit vector perpendicular to the input.
Parameters:
[v]: for Vec2, the unique (up to sign) unit vector perpendicular to v.[v1 v2]: for Vec3, the unit vector perpendicular to both v1 and v2 (normalized cross product).Only implemented for Vec2 (1-arity) and Vec3 (2-arity).
Returns a unit vector perpendicular to the input. Parameters: - `[v]`: for `Vec2`, the unique (up to sign) unit vector perpendicular to `v`. - `[v1 v2]`: for `Vec3`, the unit vector perpendicular to both `v1` and `v2` (normalized [[cross]] product). Only implemented for `Vec2` (1-arity) and `Vec3` (2-arity).
(pow v exponent)Raises every element of v to exponent, elementwise, returning a vector of the same type.
See also fastmath.core/pow.
Raises every element of `v` to `exponent`, elementwise, returning a vector of the same type. See also [[fastmath.core/pow]].
(pow10 vector)Applies fastmath.core/pow10 to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/pow10]] to every element of `v`, elementwise, returning a vector of the same type.
(prod)(prod v)Product of elements. With no arguments, returns 1.0 (the identity for multiplication).
Product of elements. With no arguments, returns `1.0` (the identity for multiplication).
(project v1 v2)Calculates the vector projection of v1 onto v2.
The projection is a vector along the direction of v2 that represents the component of v1 in that direction.
Calculates the vector projection of `v1` onto `v2`. The projection is a vector along the direction of `v2` that represents the component of `v1` in that direction.
(radians vector)Applies fastmath.core/radians to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/radians]] to every element of `v`, elementwise, returning a vector of the same type.
(real-vector v)Converts to an Apache Commons Math RealVector (ArrayRealVector). Same as vec->RealVector.
Converts to an Apache Commons Math `RealVector` (`ArrayRealVector`). Same as [[vec->RealVector]].
(reciprocal v)Reciprocal (1/x) of every element. An element equal to 0.0 produces ##Inf (or ##-Inf for -0.0), not an exception.
Reciprocal (`1/x`) of every element. An element equal to `0.0` produces `##Inf` (or `##-Inf` for `-0.0`), not an exception.
(relative-angle-between v1 v2)Returns the difference between the heading of v2 and the heading of v1.
The heading is the angle relative to the positive primary axis ([1,0,...]).
For 2D vectors, this is the difference between their polar angles.
Returns a value from -2π to 2π.
See also angle-between (absolute angle between vectors) and heading.
Returns the difference between the heading of `v2` and the heading of `v1`. The heading is the angle relative to the positive primary axis ([1,0,...]). For 2D vectors, this is the difference between their polar angles. Returns a value from -2π to 2π. See also [[angle-between]] (absolute angle between vectors) and [[heading]].
(rint vector)Applies fastmath.core/rint to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/rint]] to every element of `v`, elementwise, returning a vector of the same type.
(rotate v angle)(rotate v angle-x angle-y angle-z)Rotates v by the given angle(s), in radians.
Parameters:
[v angle]: rotates a Vec2 counter-clockwise by angle around the origin.[v angle-x angle-y angle-z]: rotates a Vec3 by successive Euler rotations around the x, y and z axes (in that order), by angle-x, angle-y and angle-z respectively.Only implemented for Vec2 (2-arity) and Vec3 (4-arity).
See also axis-rotate (rotation around an arbitrary axis).
Rotates `v` by the given angle(s), in radians. Parameters: - `[v angle]`: rotates a `Vec2` counter-clockwise by `angle` around the origin. - `[v angle-x angle-y angle-z]`: rotates a `Vec3` by successive Euler rotations around the x, y and z axes (in that order), by `angle-x`, `angle-y` and `angle-z` respectively. Only implemented for `Vec2` (2-arity) and `Vec3` (4-arity). See also [[axis-rotate]] (rotation around an arbitrary axis).
(round vector)Applies fastmath.core/round to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/round]] to every element of `v`, elementwise, returning a vector of the same type.
(safe-sqrt vector)Applies fastmath.core/safe-sqrt to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/safe-sqrt]] to every element of `v`, elementwise, returning a vector of the same type.
(sec vector)Applies fastmath.core/sec to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/sec]] to every element of `v`, elementwise, returning a vector of the same type.
(sech vector)Applies fastmath.core/sech to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/sech]] to every element of `v`, elementwise, returning a vector of the same type.
(seq->vec2 xs)Converts any sequence to a Vec2, reading its first two elements as x and y.
Missing elements default to 0.0; extra elements are ignored.
See also seq->vec3, seq->vec4, array->vec2.
Converts any sequence to a `Vec2`, reading its first two elements as `x` and `y`. Missing elements default to `0.0`; extra elements are ignored. See also [[seq->vec3]], [[seq->vec4]], [[array->vec2]].
(seq->vec3 xs)Converts any sequence to a Vec3, reading its first three elements as x, y and z.
Missing elements default to 0.0; extra elements are ignored.
See also seq->vec2, seq->vec4, array->vec3.
Converts any sequence to a `Vec3`, reading its first three elements as `x`, `y` and `z`. Missing elements default to `0.0`; extra elements are ignored. See also [[seq->vec2]], [[seq->vec4]], [[array->vec3]].
(seq->vec4 xs)Converts any sequence to a Vec4, reading its first four elements as x, y, z and w.
Missing elements default to 0.0; extra elements are ignored.
See also seq->vec2, seq->vec3, array->vec4.
Converts any sequence to a `Vec4`, reading its first four elements as `x`, `y`, `z` and `w`. Missing elements default to `0.0`; extra elements are ignored. See also [[seq->vec2]], [[seq->vec3]], [[array->vec4]].
(set-mag v len)Returns a new vector in the direction of v, with magnitude (mag) equal to len.
A negative len flips the direction instead (the resulting magnitude is abs(len), since mag is never negative).
Returns a new vector in the direction of `v`, with magnitude ([[mag]]) equal to `len`. A negative `len` flips the direction instead (the resulting magnitude is `abs(len)`, since [[mag]] is never negative).
(sfrac vector)Applies fastmath.core/sfrac to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/sfrac]] to every element of `v`, elementwise, returning a vector of the same type.
(sgn vector)Applies fastmath.core/sgn to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/sgn]] to every element of `v`, elementwise, returning a vector of the same type.
(shift v)(shift v x)Adds a value x to every element of v.
With one argument, returns v unchanged.
Adds a value `x` to every element of `v`. With one argument, returns `v` unchanged.
(sigmoid vector)Applies fastmath.core/sigmoid to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/sigmoid]] to every element of `v`, elementwise, returning a vector of the same type.
(signum vector)Applies fastmath.core/signum to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/signum]] to every element of `v`, elementwise, returning a vector of the same type.
(sim-cos v1 v2)Cosine similarity: the cosine of the angle between v1 and v2, ranging from -1 (opposite direction) to 1 (same direction), 0 when perpendicular.
Returns ##NaN if either vector is zero (undefined direction).
Cosine similarity: the cosine of the angle between `v1` and `v2`, ranging from `-1` (opposite direction) to `1` (same direction), `0` when perpendicular. Returns `##NaN` if either vector is zero (undefined direction).
(sin vector)Applies fastmath.core/sin to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/sin]] to every element of `v`, elementwise, returning a vector of the same type.
(sinc vector)Applies fastmath.core/sinc to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/sinc]] to every element of `v`, elementwise, returning a vector of the same type.
(sinh vector)Applies fastmath.core/sinh to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/sinh]] to every element of `v`, elementwise, returning a vector of the same type.
(size v)Returns elements count of the vector.
Returns elements count of the vector.
(softmax v)(softmax v t)Calculates the softmax function for the given vector v.
The softmax function transforms a vector of arbitrary real values into a probability distribution, where each element is a value between 0 and 1, and all elements sum to 1.
It has two arities:
[v]: Computes the standard softmax: softmax(v)_i = exp(v_i) / sum_j(exp(v_j)).[v t]: Computes the temperature-scaled softmax: softmax(v)_i = exp(v_i / t) / sum_j(exp(v_j / t)). The t parameter (temperature, defaults to 1) controls the shape of the output distribution; higher temperatures produce softer, more uniform distributions, while lower temperatures produce sharper distributions closer to a one-hot encoding.The implementation uses a numerically stable approach (by shifting values based on the vector's maximum) to prevent overflow when exponentiating large numbers. With infinite elements it returns the limit when one exists: a one-hot vector for exactly one ##Inf element, [1.0] for a single element; otherwise (several ##Inf, all ##-Inf, any ##NaN) the elements are ##NaN.
Returns a new vector of the same type and dimension as the input.
Calculates the softmax function for the given vector `v`. The softmax function transforms a vector of arbitrary real values into a probability distribution, where each element is a value between 0 and 1, and all elements sum to 1. It has two arities: - `[v]`: Computes the standard softmax: `softmax(v)_i = exp(v_i) / sum_j(exp(v_j))`. - `[v t]`: Computes the temperature-scaled softmax: `softmax(v)_i = exp(v_i / t) / sum_j(exp(v_j / t))`. The `t` parameter (temperature, defaults to 1) controls the shape of the output distribution; higher temperatures produce softer, more uniform distributions, while lower temperatures produce sharper distributions closer to a one-hot encoding. The implementation uses a numerically stable approach (by shifting values based on the vector's maximum) to prevent overflow when exponentiating large numbers. With infinite elements it returns the limit when one exists: a one-hot vector for exactly one `##Inf` element, `[1.0]` for a single element; otherwise (several `##Inf`, all `##-Inf`, any `##NaN`) the elements are `##NaN`. Returns a new vector of the same type and dimension as the input.
(sq vector)Applies fastmath.core/sq to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/sq]] to every element of `v`, elementwise, returning a vector of the same type.
(sqrt vector)Applies fastmath.core/sqrt to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/sqrt]] to every element of `v`, elementwise, returning a vector of the same type.
(sub v)(sub v1 v2)Subtraction of two vectors, elementwise.
With one argument, returns the negation of v (v multiplied by -1.0). When v1 and v2 are variable-length sequences of different lengths, the result is truncated to the shorter length.
Subtraction of two vectors, elementwise. With one argument, returns the negation of `v` (`v` multiplied by `-1.0`). When `v1` and `v2` are variable-length sequences of different lengths, the result is truncated to the shorter length.
(sum)(sum v)Sum of elements. With no arguments, returns 0.0 (the identity for addition).
Sum of elements. With no arguments, returns `0.0` (the identity for addition).
(tan vector)Applies fastmath.core/tan to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/tan]] to every element of `v`, elementwise, returning a vector of the same type.
(tanh vector)Applies fastmath.core/tanh to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/tanh]] to every element of `v`, elementwise, returning a vector of the same type.
(to-polar v)Converts v to polar (2d) or spherical (3d) coordinates, returned as a vector of the same type.
For Vec2: [r theta], where r is the magnitude (mag) and theta is the polar angle (heading).
For Vec3: [r theta phi], where r is the magnitude, theta is the angle from the positive z axis (0 at the north pole, π at the south pole), and phi is the azimuthal angle in the xy-plane (atan2(y, x)).
Only implemented for Vec2 and Vec3.
See also from-polar (inverse).
Converts `v` to polar (2d) or spherical (3d) coordinates, returned as a vector of the same type. For `Vec2`: `[r theta]`, where `r` is the magnitude ([[mag]]) and `theta` is the polar angle ([[heading]]). For `Vec3`: `[r theta phi]`, where `r` is the magnitude, `theta` is the angle from the positive z axis (`0` at the north pole, `π` at the south pole), and `phi` is the azimuthal angle in the xy-plane (`atan2(y, x)`). Only implemented for `Vec2` and `Vec3`. See also [[from-polar]] (inverse).
(transform v o vx vy)(transform v o vx vy vz)Transforms vector.
Maps point to a coordinate system defined by origin, vx, vy and vz (as bases).
Only for Vec2 and Vec3 types.
Transforms vector. Maps point to a coordinate system defined by origin, vx, vy and vz (as bases). Only for `Vec2` and `Vec3` types.
(triple-product a b c)Scalar triple product of three 3d vectors: a . (b x c).
Equal to the signed volume of the parallelepiped spanned by a, b and c; zero when the three are coplanar. Antisymmetric under swapping any two arguments (the sign flips).
Scalar triple product of three 3d vectors: `a . (b x c)`. Equal to the signed volume of the parallelepiped spanned by `a`, `b` and `c`; zero when the three are coplanar. Antisymmetric under swapping any two arguments (the sign flips).
(trunc vector)Applies fastmath.core/trunc to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/trunc]] to every element of `v`, elementwise, returning a vector of the same type.
(unwrap xs)(unwrap xs period)(unwrap xs period discontinuity)Unwrap by replacing large jumps (discontinuity) with their complements relative to the period.
xs - an input vectorperiod - size of wrap in the input (input span), defalut: 1.0discontinuity - maximum difference between values treated as discontinuity in wrapped input, default: period/2Returns unrwapped vector
Unwrap by replacing large jumps (discontinuity) with their complements relative to the period. * `xs` - an input vector * `period` - size of wrap in the input (input span), defalut: `1.0` * `discontinuity` - maximum difference between values treated as discontinuity in wrapped input, default: `period/2` Returns unrwapped vector
(vec->RealVector v)Converts to an Apache Commons Math RealVector (ArrayRealVector). Same as real-vector.
Converts to an Apache Commons Math `RealVector` (`ArrayRealVector`). Same as [[real-vector]].
(vec->seq v)Converts to sequence (same as seq)
Converts to sequence (same as seq)
(vec->Vec v)Converts to Clojure primitive vector Vec.
Converts to Clojure primitive vector `Vec`.
(vec->vector v)Converts to a Clojure vector, allow non-numerical entries
Converts to a Clojure vector, allow non-numerical entries
(vec2)(vec2 [x y])(vec2 x y)Creates a 2d vector (Vec2).
Accepts x and y components directly, a two-element sequence [x y], or no arguments for the zero vector [0.0 0.0].
Creates a 2d vector (`Vec2`). Accepts `x` and `y` components directly, a two-element sequence `[x y]`, or no arguments for the zero vector `[0.0 0.0]`. See also [[vec3]], [[vec4]], [[array-vec]].
(vec3)(vec3 [x y z])(vec3 v z)(vec3 x y z)Creates a 3d vector (Vec3).
Accepts x, y and z components directly, an existing Vec2 plus a z component, a three-element sequence [x y z], or no arguments for the zero vector [0.0 0.0 0.0].
Creates a 3d vector (`Vec3`). Accepts `x`, `y` and `z` components directly, an existing `Vec2` plus a `z` component, a three-element sequence `[x y z]`, or no arguments for the zero vector `[0.0 0.0 0.0]`. See also [[vec2]], [[vec4]], [[array-vec]].
(vec4)(vec4 [x y z w])(vec4 v w)(vec4 v z w)(vec4 x y z w)Creates a 4d vector (Vec4).
Accepts x, y, z and w components directly, an existing Vec3 plus a w component, an existing Vec2 plus z and w components, a four-element sequence [x y z w], or no arguments for the zero vector [0.0 0.0 0.0 0.0].
Creates a 4d vector (`Vec4`). Accepts `x`, `y`, `z` and `w` components directly, an existing `Vec3` plus a `w` component, an existing `Vec2` plus `z` and `w` components, a four-element sequence `[x y z w]`, or no arguments for the zero vector `[0.0 0.0 0.0 0.0]`. See also [[vec2]], [[vec3]], [[array-vec]].
(xlogx vector)Applies fastmath.core/xlogx to every element of v, elementwise, returning a vector of the same type.
Applies [[fastmath.core/xlogx]] to every element of `v`, elementwise, returning a vector of the same type.
(zero-count v)Counts the number of elements of v equal to 0.0.
See also nonzero-count.
Counts the number of elements of `v` equal to `0.0`. See also [[nonzero-count]].
(zero? v)Checks if every element of v is exactly 0.0. Same as is-zero?.
See also near-zero? for a tolerance-based check.
Checks if every element of `v` is exactly `0.0`. Same as [[is-zero?]]. See also [[near-zero?]] for a tolerance-based check.
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 |