Math







Pythagorean Theorem


A*A + B*B = C*C





Cartesian Coordinates






Euclidean Distance

Distance between two points P0 (x0,y0) and P1 (x1,y1):

   A = x1 - x0
   B = y1 - y0

   (x1-x0)*(x1-x0) + (y1-y0)*(y1-y0) = C*C

   dist = C = sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0))


Distance between two 3D points P0 (x0,y0,z0) and P1 (x1,y1,z1):

   dist = sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0) + (z1-z0)*(z1-z0))





Comparing Distances

sqrt is considered an expensive (i.e. slow) function

Avoid using it if you can
For example, to determine which of 2 points (P1 or P2) is closer to point P0:

  dist1 = (x1-x0)*(x1-x0) + (y1-y0)*(y1-y0) + (z1-z0)*(z1-z0)
  dist2 = (x2-x0)*(x2-x0) + (y2-y0)*(y2-y0) + (z2-z0)*(z2-z0)
  if dist1 < dist2:
        P1 is closer
  else:
        P2 is closer





Trigonometry

sin(A) = opposite / hypotenuse
cos(A) = adjacent / hypotenuse
tan(A) = opposite / adjacent

or

opposite = hypotenuse * sin(A)
adjacent = hypotenuse * cos(a)





Trigonometry

x = radius * cos(A)
y = radius * sin(A)





Radians

Standard math library functions use radians

360 degrees = 1 full circle = 2 π radians

(Circumference of unit circle = 2 π)


    radians = degrees / 360.0 * 2 * pi

or

    radians = degrees / 180.0 * pi
(or use Python's pre-defined functions math.radians(d) and math.degrees(r))




Making a Circle

    vertices = []
    for degrees in range(0, 360): 
        angleInRadians = math.radians(degrees)
        x = math.cos(angleInRadians) * radius
        y = math.sin(angleInRadians) * radius
        vertices += [x,y]
    vlist = pyglet.graphics.vertex_list(360, ('v2f', vertices))





Driving

Vehicle has direction and speed of travel

Direction is orientation - rotation about Z

To move forward:

    distance = speed * time

    dx = math.cos(direction) * distance
    dy = math.sin(direction) * distance

    x = x + dx
    y = y + dy





atan2

atan2 converts from (X,Y) coordinates back to angles

Note: it takes arguments in the order Y, X

 
    angle = math.degrees( math.atan2(y,x) )





Interpolation

Deriving a value for something from two pre-defined values (extremes)

e.g. Moving object from one position to another, over time






Linear Interpolation

Interpolation expressed as fractional distance between the two extremes

Ranges from 0.0 to 1.0
0.0 = first point; 1.0 = second point






Linear Interpolation

For a single value, with extremes V0 & V1 and interpolation fraction A:

    V = (1 - A) * V0 + A * V1


For multiple values, such as XYZ position, use the same fraction A for all:

    X = (1 - A) * X0 + A * X1
    Y = (1 - A) * Y0 + A * Y1
    Z = (1 - A) * Z0 + A * Z1





Timing

To interpolate over time, compute interpolation fraction based on the amount of time that has passed.

Example:

    def startAnimation():
        animating = True
        startTime = time.time()
        duration = 5

    def computeAnimation():
        if animating:
            t = time.time() - startTime
            if t <= duration:
                a = t / duration
            else:
                animating = False
                a = 1
            x = (1-a)*startX + a*endX
            y = (1-a)*startY + a*endY
            z = (1-a)*startZ + a*endZ





Timing

Linear Slow-in Slow-out
X = tX = -2*t*t*t + 3*t*t
A2 = -2*A*A*A + 3*A*A
V = (1-A2) * V0 + A2 * V1





Randomness

We often would like the behavior of a program to change or be unpredictable - to not be exactly the same every time we run it.

In other cases, randomness helps eliminate unwanted artifacts, such as obvious, excessively regular or repeated patterns. These include patterns in the appearance and in the movement of objects.






Randomness

Things that can be randomized include:






Random Number Functions

Randomness is added to programs by using random numbers. These are generated by random number functions.

Javascript provides a random function in the Math module.

Math.random()
Returns a random floating point number between 0 and 1.

Python has a package called random.
Two of the functions it provides are:

random()
Returns a random floating point number between 0 and 1.
uniform(a,b)
Returns a random floating point number between a and b.





Random Number Functions

In C, the standard random number functions are:

random()
Returns a random integer between 0 and RAND_MAX
drand48()
Returns a random float between 0 and 1





Distributions

Random numbers can come in different distributions - how frequently the various numbers occur.

e.g. rolling a fair die many times will yield roughly the same number of 1s, 2s, 3s, 4s, 5s, and 6s.
A loaded die can produce one number more frequently.

random() & uniform() return uniform distributions - each possible number is equally likely to be returned.
If you call the function a large number of times, then you can expect each possible number to be returned about (but not exactly) the same number of times.
(Flipping a coin 1,000,000 times, you would expect to get roughly 500,000 heads and 500,000 tails.)

This plot is from calling int(random() * 100) 100,000 times. It shows how many times each of the possible values (from 0 to 99) was returned.






Distributions

Sometimes we want a different distribution.

A common distribution is the bell curve (or gaussian distribution). In this distribution, one small range of numbers is returned more frequently than others, with values further from the center of the distribution returned less and less frequently.






Gaussian Distribution

The Python function random.gauss(center, deviation) returns random numbers in a gaussian distribution.

The first argument (center) is the central number that the return values will be clustered around. The second argument (deviation) is the standard deviation of the distribution - this measures how broad the bell curve is; roughly 2/3 of all returned values will be within +/- deviation of the center value.

Example: a gaussian distribution lets you place objects randomly, but clustered about a center.

UniformGaussian





choice

Python's random.choice(list) randomly chooses one element from a list.

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f']
>>> random.choice(letters)
'a'
>>> random.choice(letters)
'e'
>>> random.choice(letters)
'b'
>>> random.choice(letters)
'b'





shuffle

Python's random.shuffle(list) randomly re-orders a list (in place).

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f']
>>> random.shuffle(letters)
>>> letters
['f', 'e', 'd', 'c', 'b', 'a']
>>> random.shuffle(letters)
>>> letters
['c', 'b', 'a', 'd', 'e', 'f']


Creative Commons License
This document is by Dave Pape, and is released under a Creative Commons License.