CodeViking Math Documentation

A collection of mathematical utility funcitons.

This package currently supports Python 3 only. There is no planned support for Python 2. Patches that provide Python 2 compatibility are welcome.

WARNING: Code and documentation are currently in beta testing. Everything documented here is expected to work, but not all features have been thoroughly tested yet. If you find any bugs, please file a bug report. at https://bitbucket.org/codeviking/python-codeviking.math/

codeviking.math Package

Numerical Comparison Functions

Comparing floating-point numbers for equality can be problematic. Testing for exact equality is usually not a good idea. Instead, we usually want to consider two values equal if they are very close. The functions in this module can be used to create comparison functions that tolerate a user-specified amount of error.

Definitions:

Relative Difference
\(\textrm{rel_diff}(a, b) = \frac{\left| a - b \right|}{\max\left( |a|,|b|\right)}\)
Absolute Difference
\(\textrm{abs_diff}(a, b) = |a - b|\)
make_absolute_equals(tol)[source]

Create a comparison function is_equal(a,b) that returns True if \(\textrm{abs_diff}(a, b) \leq tol\)

Parameters:tol (float) – absolute tolerance
Returns:function that returns True if absolute difference between a and b is less than tol.
Return type:(float, float) -> bool
make_equals(abs_tol, rel_tol)[source]
Create a comparison that returns True if either
\(\textrm{rel_diff}(a, b) \leq \textit{rel_tol}\) or \(\textrm{ rel_diff}(a, b) \leq \textit{abs_tol}\)
Parameters:
  • abs_tol (float) – absolute tolerance
  • rel_tol (float) – relative tolerance
Returns:

function that returns True if either the relative difference is

less than rel_tol or absolute difference is less than abs_tol :rtype: (float, float) -> bool

make_relative_equals(tol)[source]

Create a comparison function is_equal(a,b) that returns True if \(\textrm{rel_diff}(a, b) \leq tol\)

Parameters:tol (float) – relative tolerance
Returns:function that returns True if relative difference between a and b is less than tol.
Return type:(float, float) -> bool
make_seq_equals(eq_func)[source]

Create a comparison function that compares corresponding elements of two sequences. Two sequences are considered equal if they have the same length, and \(\textrm{eq_func}(a_i, b_i) \forall i=0, ..., n\)

Parameters:equals_func ((float, float) -> bool) – The function used to compare elements
Returns:comparison function
Return type:(list[float], list[float]) -> bool

Easing Functions

Easing functions are smooth, real valued functions defined over the range [0, 1]. Behavior outside this interval is not specified. See http://robertpenner.com/easing/ for more info. Each of these functions takes a single float in [0, 1] and returns a float in [0, 1].

function type in function out function in-out function
linear linear linear linear
2nd degree polynomial in_p2 out_p2 in_out_p2
3rd degree polynomial in_p3 out_p3 in_out_p3
4th degree polynomial in_p4 out_p4 in_out_p4
5th degree polynomial in_p5 out_p5 in_out_p5
circular in_circ out_circ in_out_circ
sin in_sin out_sin in_out_sin
exp in_exp out_exp in_out_exp
in_circ(t)[source]
in_exp(alpha)[source]
in_out_circ(t)[source]
in_out_exp(alpha)[source]
in_out_p2(t)[source]
in_out_p3(t)[source]
in_out_p4(t)[source]
in_out_p5(t)[source]
in_out_sin(t)[source]
in_p2(t)[source]
in_p3(t)[source]
in_p4(t)[source]
in_p5(t)[source]
in_sin(t)[source]
linear(t)[source]
out_circ(t)[source]
out_exp(alpha)[source]
out_p2(t)[source]
out_p3(t)[source]
out_p4(t)[source]
out_p5(t)[source]
out_sin(t)[source]

Functions

This module contains functions that are used to create other functions. Clamping and mixing functions are provided, as are transition functions and piecewise function assembly.

make_bump_func(x0, x1, x2, y0, y1, y2)[source]

Create a bump function with the following properties:

  • f(x)=y0 for x≤x0
  • f(x1)=y1
  • f(x)=y2 for x2≤x
  • f’(x) = 0 for x=x0, x=x1, x=x2.
  • in the interval [x0,x1], smoothly and monotonically transition between y0 and y1.
  • in the interval [x1,x2], smoothly and monotonically transition between y1 and y2.
make_clamp(x0, x1)[source]

Create a clamping function that clhtamps input values to the range [x0,x1].

make_interval_func(x0, x1, y0, f, y1)[source]

Create function on the interval [x0,x1] with constant value outside that interval:

  • y0 for x < x0
  • f(x) for x0 ≤ x < x1
  • y1 for x1 ≤ x
make_map_from_01(t0, t1)[source]

Create a function that linearly maps 0.0->t1 and 1.0->t1.

Parameters:
  • t0 (float) – value that 0.0 maps to
  • t1 (float) – value that 1.0 maps to
Return type:

(float) -> float

make_map_from_01c(t0, t1)[source]

Clamped version of make_map_from_01. The resulting function will always return a value in [t0, t1].

Parameters:
  • t0 (float) – value that 0.0 maps to
  • t1 (float) – value that 1.0 maps to
Return type:

(float) -> float

make_map_to_01(t0, t1)[source]

Create a function that linearly maps t0->0.0 and t1->1.0. This function is undefined when t0==t1. Nevertheless, we return a function that always returns 0.0 when t0==t1. This means that if you construct a forword map f= make_map_to_01(t0,t0) and a reverse map g = make_map_from_01(t0, t0), then their composition will behave sensibly: g(f(t)) == t0.

Parameters:
  • t0 (float) – value that maps to 0.0
  • t1 (float) – value that maps to 1.0
Return type:

(float) -> float

make_map_to_01c(t0, t1)[source]

Clamped version of make_map_to_01. The resulting function will always return a value in [0.0, 1.0].

Parameters:
  • t0 (float) – value that maps to 0.0
  • t1 (float) – value that maps to 1.0
Return type:

(float) -> float

make_mix(y0, y1)[source]

Create a mix function that mixes between y0 and y1 as x varies between 0 and 1.

  • y0 for x0 ≤ 0
  • y1 for 1 ≤ x
  • y0 + x*(y1-y0) for x ∈[0,1]
make_rect_func(x0, x1, y0, y1, y2)[source]

Create rect function ( ┌─┐ )on the interval [x0,x1]:

  • y0 for x < x0
  • y1 for x0 ≤ x ≤ x1
  • y2 for x1 < x
make_smooth_step(x0, x1, y0=0.0, y1=1.0)[source]

Creates a smooth step function f with the following properties:

  • f(x)=y0 for x ≤ x0
  • f(x)=y1 for x1 ≤ x
  • f’(x) = 0 for x=x0 and x=x1.
  • in the interval [x0,x1], the function smoothly transitions between y0 and y1. We use a monotonically increasing sin function on this interval.
make_step(x0, y0=0.0, y1=1.0)[source]

create a step function:

  • f(x) = y0 for x<x0
  • f(x) = y1 for x0≤x
make_triangle_func(x0, x1, x2, y0, y1, y2)[source]

Create triangle function ( ╱╲ ) on the interval [x0,x2]:

  • y0 for x < x0
  • linear slope from (x0,y0) to (x1,y1) for x0 ≤ x < x1
  • linear slope from (x1,y1) to (x2,y2) for x1 ≤ x < x2
  • y2 for x2 ≤ x
min_max(a, b)[source]

Return (a, b) in order: ( min(a,b), max(a,b) )

Returns:min(a,b), max(a,b)
Return type:float, float
piecewise_func1(x0, f0, f1)[source]

Create a piecewise function with one knot:

  • f0(x) for x < x0
  • f1(x) for x0 ≤ x
Parameters:
  • x0 (float) – knot between f0 and f1
  • f0 ((float) -> object) – function to use for x < x0
  • f1 ((float) -> object) – function to use for x0 ≤ x
Returns:

piecewise function

Return type:

(float) -> float

piecewise_func2(x0, x1, f0, f1, f2)[source]
Create a piecewise function with two knots:
  • f0(x) for x < x0
  • f1(x) for x0 ≤ x < x1
  • f2(x) for x1 ≤ x
Parameters:
  • x0 (float) – knot between f0 and f1
  • x1 (float) – knot between f1 and f2
  • f0 ((float) -> object) – function to use for x < x0
  • f1 ((float) -> object) – function to use for x0 ≤ x < x1
  • f2 ((float) -> object) – function to use for x1 ≤ x
Returns:

piecewise function

Return type:

(float) -> float

2D Geometry

This module contains types useful in 2D geometry.

class Box2[source]

Axis-aligned bounding box. :members: :undoc-members: :inherited-members:

xr, yr

x and y intervals (instances of class RI) of this bounding box. These attributes are read-only.

p in box

True if the point p lies inside box. p can be a V2 or tuple. A p is inside box if box.xr.min <= p.x <= box.xr.max and box.yr.min <= p.y <= box.yr.max

__init__

Initialize self. See help(type(self)) for accurate signature.

static __new__(xr, yr)[source]
bbox
count(value) → integer -- return number of occurrences of value
empty = Box2(xr=RI(min=inf, max=-inf), yr=RI(min=inf, max=-inf))
expand(item)[source]

return a Box2 that contains both this box and item.

Parameters:item – can be either a V2, a Box2, or a tuple of length 2
index(value[, start[, stop]]) → integer -- return first index of value.

Raises ValueError if the value is not present.

intersection(other)[source]
intersects(other)[source]
is_empty

return True if this box is empty.

xr

Alias for field number 0

yr

Alias for field number 1

class ClipLine[source]

Create new instance of ClipLine(a, b, n)

__init__

Initialize self. See help(type(self)) for accurate signature.

__new__(_cls, a, b, n)

Create new instance of ClipLine(a, b, n)

a

Alias for field number 0

b

Alias for field number 1

count(value) → integer -- return number of occurrences of value
index(value[, start[, stop]]) → integer -- return first index of value.

Raises ValueError if the value is not present.

n

Alias for field number 2

class ClipResult(sa, sb, i)

Create new instance of ClipResult(sa, sb, i)

__init__

Initialize self. See help(type(self)) for accurate signature.

static __new__(_cls, sa, sb, i)

Create new instance of ClipResult(sa, sb, i)

count(value) → integer -- return number of occurrences of value
i

Alias for field number 2

index(value[, start[, stop]]) → integer -- return first index of value.

Raises ValueError if the value is not present.

sa

Alias for field number 0

sb

Alias for field number 1

class ConvPoly2[source]

2d Convex Polygon Vertices must be supplied in counter clockwise (CCW) order.

vertices

Triangle vertices in counter clockwise order.

onorms

Outward-facing edge normal vectors.

p in poly

True if point p lies inside poly. p can be a V2 or a tuple.

__init__

Initialize self. See help(type(self)) for accurate signature.

static __new__(vertices)[source]
bbox

Alias for field number 2

count(value) → integer -- return number of occurrences of value
index(value[, start[, stop]]) → integer -- return first index of value.

Raises ValueError if the value is not present.

onorms

Alias for field number 1

segments
vertex(idx)[source]
vertices

Alias for field number 0

class Segment2[source]

Create new instance of Segment(a, b)

__init__

Initialize self. See help(type(self)) for accurate signature.

__new__(_cls, a, b)

Create new instance of Segment(a, b)

a

Alias for field number 0

b

Alias for field number 1

count(value) → integer -- return number of occurrences of value
index(value[, start[, stop]]) → integer -- return first index of value.

Raises ValueError if the value is not present.

intersect(other, epsilon_sqr=1e-08)[source]
point(alpha)[source]

Calculate a point on the segment that is a fraction alpha between a and b. point(0) == a point(1) == b point(0.5) == midpoint of a, b.

side(point)[source]

Which side of this line segment is point on? > 0 => point is on the right side. < 0 => point is on the left side.

v
class Shape2[source]

This is an interface for a generic 2d shape. It only supports one operation:

subclasses need to implement the __contains__ member function.

__init__

Initialize self. See help(type(self)) for accurate signature.

__new__()

Create and return a new object. See help(type) for accurate signature.

class Tri2[source]

2d Triangle. Vertices must be supplied in counter clockwise (CCW) order.

v0, v1, v2

Triangle vertices in counter clockwise order. These are read-only attributes

n0, n1, n2

Outward-facing edge normal vectors. These are read-only attributes

p in triangle

True if point p lies inside triangle. p can be a V2 or a tuple.

__init__

Initialize self. See help(type(self)) for accurate signature.

static __new__(v0, v1, v2)[source]
bbox

Alias for field number 6

count(value) → integer -- return number of occurrences of value
index(value[, start[, stop]]) → integer -- return first index of value.

Raises ValueError if the value is not present.

n0

Alias for field number 3

n1

Alias for field number 4

n2

Alias for field number 5

v0

Alias for field number 0

v1

Alias for field number 1

v2

Alias for field number 2

class V2[source]

2D Euclidean vector type.

Several operations are supported. In the following, u is a V2, v is either a V2 or a tuple of length 2, and a is a number.

  • u == v : standard equality test.
  • u + v : vector addition
  • u - v : vector subtraction
  • u * a or a * u : scalar multiplication
  • u / a : scalar division
  • u // a : scalar floor division
  • u @ v : dot product

Create new instance of P2(x, y)

__init__

Initialize self. See help(type(self)) for accurate signature.

__new__(_cls, x, y)

Create new instance of P2(x, y)

count(value) → integer -- return number of occurrences of value
dot(other)[source]

Dot product (other can be a V2 or a tuple).

index(value[, start[, stop]]) → integer -- return first index of value.

Raises ValueError if the value is not present.

ldot(other)[source]

Dot product of the left-facing normal vector with other.

length

Euclidean length of this vector.

lnormal

left-handed normal vector (points to the right of this direction vector.

rdot(other)[source]

Dot product of the right-facing normal vector with other.

rnormal

right-handed normal vector (points to the right of this direction vector.

unit

Returns a normalized version of this vector (unit vector).

x

Alias for field number 0

y

Alias for field number 1

Linear Algebra

tridiag_solve(a, b, c, y)[source]

Calculate the solution of a tridiagonal system of linear equations. Consider the linear system:

\[\mathbf{M} \cdot \mathbf{x} = \mathbf{y}\]

Where the matrix \(\mathbf{M}\) is a tridiagonal matrix with the following form:

\[\begin{split}\left( \begin{matrix} b_0 & c_0 & & & & 0 \\ a_1 & b_1 & c_1 & & & \\ & a_2 & b_2 & c_2 & & \\ & & \ddots & \ddots & \ddots & \\ & & & a_{n-2}& b_{n-2}& c_{n-2} \\ 0 & & & & a_{n-1}& b_{n-1} \end{matrix} \right) \cdot \left( \begin{matrix} x_0 \\ x_1 \\ x_2 \\ \vdots \\ x_{n-2}\\ x_{n-1} \end{matrix} \right) = \left( \begin{matrix} y_0 \\ y_1 \\ y_2 \\ \vdots \\ y_{n-2}\\ y_{n-1} \end{matrix} \right)\end{split}\]

Note that elements \(a_0\) and \(c_{n-1}\) are not used.

This function returns the vector \(\mathbf{x}\).

Parameters:
  • a (Seq[float]) – subdiagonal
  • b (Seq[float]) – diagonal
  • c (Seq[float]) – superdiagonal
  • y (Seq[float]) – rhs
Returns:

solution to the tridiagonal system

Return type:

Seq[float]

Primitive Functions

This module contains primitive functions designed to be used in the creation of more complex functions.

bump(x)[source]

Smooth step up on the interval [-1,0], and down on [0,1]. Clamp to 0.0 outside the interval. This is the clamped version of [smooth010].

Return type:float
clamp(x, x0, x1)[source]

Clamp x to lie within the interval [x0, x1]

Parameters:
  • x (float) – the value to clamp
  • x0 (float) – left edge of the interval
  • x1 (float) – right edge of the interval
Returns:

x restricted to [x0, x1]

Return type:

float

clamp01(x)[source]

Clamp input value to [0.0, 1.0]

rect(x)[source]

The rect function defined as:

  • 1 for -½ ≤ x ≤ ½
  • 0 otherwise.
smooth010(x)[source]

Smooth step up on the interval [-1,0], and down on [0,1].

WARNING: this function is also defined outside the interval [-1,1]. It is intended to be used as a primitive to build other functions, so for efficiency reasons, it is not clamped or otherwise modified.

smooth101(x)[source]

Smooth step down on the interval [-1,0] and up on [0,1].

WARNING: this function is also defined outside the interval [-1,1]. It is intended to be used as a primitive to build other functions, so for efficiency reasons, it is not clamped or otherwise modified.

smooth_step_down(x)[source]

Step up from 0 to 1 on the interval [0,1], and clamp to 0.0 and 1.0 outside the interval.

Return type:float
smooth_step_up(x)[source]

Step up from 0 to 1 on the interval [0,1], and clamp to 0.0 and 1.0 outside the interval.

Return type:float
wrap_to_centered_interval(x, center, half_width)[source]

Given an interval [center-halfWidth, center+halfWidth), map x to this interval by assuming the interval repeats infinitely.

wrap_to_interval(x, x0, s)[source]

Given an interval [x0,x0+s), map x to this interval by assuming the interval repeats its values on this infinitely in both directions.

Indices and tables