Math module

normalize

procedure · 2 overloadsSource

Scales a vector or quaternion to length 1. Given a pointer it normalizes in place and returns the length it had; given a value it returns the normalized copy.

If the length is not above epsilon (default 0, so only an exactly zero length), the vector is not scaled: it is replaced by fallback (default all zeros). The comparison is against the rounded float length. Components are scaled at float64 precision, so tiny and huge vectors keep their direction. A Plane3 is normalized by its normal's length, so the normal is unit length and the plane stays the same plane.

ExampleOpen in playground ↗
v := xyz(0, 3, 4);
n := normalize(*v);
assert(n == 5 && v == xyz(0, 0.6, 0.8));
assert(normalize(xy(0, 2)) == xy(0, 1));
w := xy(0, 0);
normalize(*w, fallback = xy(1, 0));
assert(w == xy(1, 0));
normalize :: (v: *$T/MyVectors, epsilon := 0.0, fallback := T.{}) -> float

Scales *v to length 1 in place and returns its old length. A length at or below epsilon is treated as zero: *v becomes fallback and that length is still returned.

Parameters

v: *$T/MyVectors
the vector to normalize.
epsilon := 0.0
lengths up to this value count as zero.
fallback := T.{}
what *v is set to when the length counts as zero.

Returns

float
normalize :: (v: $T/MyVectors, epsilon := 0.0, fallback := T.{}) -> T

Returns a copy of v scaled to length 1. A length at or below epsilon is treated as zero and fallback is returned instead.

Parameters

v: $T/MyVectors
the vector to normalize.
epsilon := 0.0
lengths up to this value count as zero.
fallback := T.{}
what is returned when the length counts as zero.

Returns

T

See also