Probably Dance

I can program and like games

Category: Math

Transform Matrices are Great and You Should Understand Them

The title of this blog post is obvious for any game programmer, but I notice that people outside of games often write clumsy code because they don’t know how transform matrices work. Especially when people do some simple 2D rendering code, like if you just want to quickly visualize some data in a HTML canvas. People get tripped up on transform math a lot. As an example imagine drawing this simple graph:

It’s just an arbitrary graph with arbitrary numbers, the point is all the layout decisions that happened here: E.g. “Long First Label” extends to the left and pushes everything else over to the right by a bit. If you aren’t organized about how to express your transforms, your code ends up with lots of arbitrary offsets and multipliers. You can’t even calculate where to draw the labels on the y-axis without including an offset for potentially long labels on the x-axis. (and long labels on the y-axis can push over the x-axis, too. Uh-oh) Your first choice for visualization should probably be an existing tool (like I used to generate the graph above) but surprisingly often you’ll want to do something custom, and then you have to worry about transforms.

Game programmers have to do complicated transforms all the time, so they had to get organized about this and the result is the transform matrix. It’s remarkably simple and every programmer should probably know it, just to appreciate its beauty. There are two tricks to transform matrices:

Read the rest of this entry »

A Logarithm is Just the Number of Digits

If you don’t have a good intuition for how logarithms work, (e.g. what does it mean that happiness scales with the log of income? Or why does an algorithm that runs in log(log(x)) steps always run in 5 steps or fewer?) here is how you can explain it to a third grader: It’s the number of digits (roughly). For example it’s the number of zeros in these:

log_{10}(100) = 2

log_{10}(1000) =3

log_{10}(0.01) = -2

log_{10}(0.001) = -3

For this to work out we have to transition through zero: log(1)=0

If it bothers you that I’m off by one, because clearly 100 has 3 digits, not 2, you can get the actual number of digits by rounding away from 0 to the next integer.

Where it gets complicated is when you have a number between two round numbers:

log_{10}(123) = ?

We can’t just count the number of digits. It’s got to be somewhere between the other two numbers, coming out to roughly 2.09. But lets not worry about those odd cases for now. Where this really helps is when trying to build an intuition for the logarithm rules:

Read the rest of this entry »