Skip to content

pymath.normalize

Daniel Flassig edited this page Jul 17, 2026 · 2 revisions

Returns the given vector scaled to unit length, or nil if the vector is too short to normalize reliably.

u = pymath.normalize(v [, threshold])
Parameter Type Description
v vector A vector of any dimension.
threshold number (optional) Non-negative length at or below which the vector counts as too short. Default: an implementation defined tolerance.

Return value

Type Description
u A new vector `v /

Notes:

  • v is not modified.
  • Use the nil return to catch degenerate input (e.g. a zero direction vector) instead of dividing by a near-zero length yourself.
  • The length computation is overflow-safe, like pymath.length. nil is also returned if the length overflows or the input is not finite.
  • The components of the result are guaranteed to lie in [-1, 1] even in floating point, so they can be passed straight to ACOS / ASIN.
  • A threshold of 0 is allowed and rejects exactly the zero vector: even vectors of subnormal length are normalized correctly

Example:

local dir = pymath.normalize({3, 4})
-- dir == {0.6, 0.8}

pymath.normalize({0, 0, 0})
-- nil                          -- the zero vector cannot be normalized

pymath.normalize({1e-9, 0, 0}, 1e-6)
-- nil                          -- below the explicit threshold

Version Support:

Minimum PYTHA Version: V27

See also:

pymath, pymath.length, pymath.cross

Clone this wiki locally