Python: 2D Rotation and Scaling in Less Than 1 KB

This code isn't super complicated, but has the potential to be quite useful and also quite fast. For those wondering why it works, see complex numbers on Wikipedia. The specific section of interest is "multiplication and division in polar form." I cannot yet produce the formulas heere as I have just realized I have no support for LaTeX and, because of the poor state of math accessibility everywheree, I need to find one that preserves the LaTeX as alt text.

Anyhow, here's the actual code itself:

"""2D transformation library.
Vectors are tuples: (x, y).
Make_rotation takes an angle in degrees, returning a transform that can rotate a vector by degrees.  Negative values are allowed.
Make_scale returns a transform that scales a vector's magnitude.
Multiplying transformations produces a transform that does everything as if they had all been applied separately.
Call apply_transformation to actually use your transform.  Transforms are valid forever.
"""

from math import sin, cos, pi

def make_rotation(degrees):
    rads = degrees/180.0*pi
    return cos(rads)+sin(rads)*1j

#for clarity
def make_scale(factor):
    return factor

def apply_transform(vector, transform):
    result = (vector[0]+vector[1]*1j)*transform
    return result.real, result.imag

Comments