generativepy.math module

By Martin McBride, 2023-04-27
Tags: formula tex latex
Categories: generativepy generative art


The math module provides 2D vector and matrix implementations.

It includes:

  • Matrix 2D matrix implementation.
  • Vector 2D vector implementation.

Both of these classes are immutable.

Utility functions

isclose

def isclose(a, b)

Tests if two numbers are almost equal.

This will return true if either:

  • The absolute difference between a and b is less than 1e-9 times the magnitude of the absolute largest of the two.
  • The absolute difference between a and b is less than 1e-10.

Matrix

The Matrix class has a number of static method, instance methods, and supports several built-in operators and functions.

staticmethod scale

Creates a scaling Matrix.

scale(scale_x, scale_y=None)
Parameter Type Description
scale_x Number Scale factor in x direction
scale_y Number Scale factor in y direction, optional

Creates a scaling matrix to scale by scale_x in the x direction and scale_y in the y direction.

If scale_y is not supplied, the matrix will scale by scale_x in both directions.

staticmethod scale

Creates a translation Matrix.

translate(x, y)
Parameter Type Description
x Number Translation in x direction
y Number Translation in y direction

Creates a transation matrix to translate by (x, y).

staticmethod rotate

Creates a rotation Matrix.

rotate(angle)
Parameter Type Description
angle Number Rotation angle in radians
y Number Translation in y direction

Creates a rotation matrix to translate by angle radians, counterclockwise.

staticmethod multiply

Multiply two matrices

multiply(p, q)
Parameter Type Description
p Matrix First matrix
q Matrix Second matrix

Returns a mtrix representing the matrix product p times q.

Constructor

Creates a matrix.

Matrix(xx, xy, xt, yx, yy, yt)

Creates a matrix with elements xx, xy, xt, yx, yy, yt.

Standard operators

The Matrix class supports a number of operators and built-in functions.

Variables used inn the examples:

  • p and q are Matrix objects.
  • v is a vector object.
  • n is a number (int or float).

Operator examples:

p + q      # Matrix addition.
p - q      # Matrix subtraction.
-p         # Matrix negation.
p * q      # Matrix multiplication.
p * n      # Matrix multiplied by number.
n * p      # Matrix multiplied by number.
p / n      # Matrix divided by number.
p // n     # Matrix floor divided by number.
p == q     # Test for equality, uses the `is_close` function on each corresponding pair of elements.
p[n]       # nth element of p. n must be an integer between 0 and 5 inclusive.

Built-in function examples:

len(p)     # Number of elements in p, always 6
iter(p)    # Return an iterator that iterates over the 6 values in p then stops.
str(p)     # Strinp representation of p

Vector

The Vector class has a number of static method, instance methods, properties, and supports several built-in operators and functions.

staticmethod polar

Creates a Vector based on polar parameters.

polar(length, angle)
Parameter Type Description
length Number Length of the vector
angle Number Angle of vector in radians

Create a vector of length length pointing in directio of angle, measured in radians counterclockwise from x-axis.

staticmethod matrix_premultiply

Creates a Vector from an existing vector, premultiplied by a matrix.

matrix_premultiply(m, v)
Parameter Type Description
m Matrix
v Vector

Create a vector that is the result of multiplying v by m.

This is equivalent to either of the following:

m * v
v.transform(m)

Constructor

Creates a vector.

Vector(x, y)
Vector(seq)
Parameter Type Description
x Number x coordinate
y Number y coordinate
seq Sequence Sequence of exactly 2 numbers

A Vector can be constructed from 2 numbers, x and y.

Alternatively it can be constructed from a sequence wih exactly 2 number elements. This could be a list, a tuple, another Vector, or any other sequence.

transform

    transform(m)
Parameter Type Description
m Matrix

Create a Vector that is the result of multiplying this Vector by m.

scale

    scale(scale_x, scale_y=None)
Parameter Type Description
scale_x Number Scaling factor in x-direction
scale_y Number Scaling factor in y-direction

Create a Vector that is the result of scaling this Vector by scale_x in the x-direction and scale_y in the y-direction.

If scale_y is None, the vector will be scaled by scale_x in both directions.

translate

    translate(x, y)
Parameter Type Description
x Number x distance
y Number y distance

Translate a Vector by (x, y). This adds (x, y) to the original vector, and return it as a new vector.

rotate

    rotate(angle)
Parameter Type Description
angle Number Angle in radians

Create a Vector that is the result of rotating this Vector by angle radians counterclockwise about the origin.

lerp

    lerp(other, factor)
Parameter Type Description
other Vector Other vector
factor Number Interpolation factor

Interpolates between this vector and other. For example:

  • factor 0 returns a vector equal to this vector.
  • factor 0.5 returns a vector half way between other and this vector.
  • factor 1 returns a vector equal to other.

Factor can also be less than 0 or greater than 1.

property x

For vector v, the property v.x returns the x-value of the vector. It is equivalent to v[0].

property y

For vector v, the property v.y returns the y-value of the vector. It is equivalent to v[1].

property length

For vector v, the property v.length returns the length of the vector.

property angle

For vector v, the property v.angle returns the angle that the vector makes with the x-axis.

It is undefined for the vector (0, 0).

property unit

For vector v, the property v.unit returns a vector of unit length, in the same direction as v.

It is undefined for the vector (0, 0).

Standard operators

The Vector class supports a number of operators and built-in functions.

Variables used inn the examples:

  • m ia a Matrix objects.
  • u and v are vector objects.
  • n is a number (int or float).

Operator examples:

u + v      # Vector addition.
u - v      # Vector subtraction.
-u         # Vector negation.
m * u      # Multiply matrix by vector.
u * n      # Vector multiplied by number.
n * u      # Vector multiplied by number.
u / n      # Vector divided by number.
u // n     # Vector floor divided by number.
u == v     # Test for equality, uses the `is_close` function on each corresponding pair of elements.
u[n]       # nth element of u. n must be an integer between 0 and 1 inclusive.

Built-in function examples:

len(u)     # Number of elements in u, always 2
iter(u)    # Return an iterator that iterates over the 2 values in u then stops.
str(u)     # String representation of u

See also

If you found this article useful, you might be interested in the book NumPy Recipes or other books by the same author.

Join the PythonInformer Newsletter

Sign up using this form to receive an email when new content is added:

Popular tags

2d arrays abstract data type alignment and angle animation arc array arrays bar chart bar style behavioural pattern bezier curve built-in function callable object chain circle classes clipping close closure cmyk colour combinations comparison operator comprehension context context manager conversion count creational pattern data science data types decorator design pattern device space dictionary drawing duck typing efficiency ellipse else encryption enumerate fill filter font font style for loop formula function function composition function plot functools game development generativepy tutorial generator geometry gif global variable gradient greyscale higher order function hsl html image image processing imagesurface immutable object in operator index inner function input installing iter iterable iterator itertools join l system lambda function latex len lerp line line plot line style linear gradient linspace list list comprehension logical operator lru_cache magic method mandelbrot mandelbrot set map marker style matplotlib monad mutability named parameter numeric python numpy object open operator optimisation optional parameter or pandas partial application path pattern permutations pie chart pil pillow polygon pong positional parameter print product programming paradigms programming techniques pure function python standard library radial gradient range recipes rectangle recursion reduce regular polygon repeat rgb rotation roundrect scaling scatter plot scipy sector segment sequence setup shape singleton slice slicing sound spirograph sprite square str stream string stroke structural pattern subpath symmetric encryption template tex text text metrics tinkerbell fractal transform translation transparency triangle truthy value tuple turtle unpacking user space vectorisation webserver website while loop zip zip_longest