# psychopy.tools.mathtools.normalize¶

psychopy.tools.mathtools.normalize(v, out=None, dtype=None)[source]

Normalize a vector or quaternion.

varray_like

Vector to normalize, can be Nx2, Nx3, or Nx4. If a 2D array is specified, rows are treated as separate vectors. All vectors should have nonzero length.

outndarray, optional

Optional output array. Must be same shape and dtype as the expected output if out was not specified.

dtypedtype or str, optional

Data type for computations can either be ‘float32’ or ‘float64’. If out is specified, the data type of out is used and this argument is ignored. If out is not provided, ‘float64’ is used by default.

Returns

Normalized vector v.

Return type

ndarray

Notes

• If the vector has length is zero, a vector of all zeros is returned after normalization.

Examples

Normalize a vector:

v = [1., 2., 3., 4.]
vn = normalize(v)


The normalize function is vectorized. It’s considerably faster to normalize large arrays of vectors than to call normalize separately for each one:

v = np.random.uniform(-1.0, 1.0, (1000, 4,))  # 1000 length 4 vectors
vn = np.zeros((1000, 4))  # place to write values
normalize(v, out=vn)  # very fast!

# don't do this!
for i in range(1000):
vn[i, :] = normalize(v[i, :])