Checkerboard algorithm?

Started by
2 comments, last by frob 10 years, 2 months ago

Hi everyone!

I'm looking to create a function which simulates a checkerboard, i.e. returns 0 for a black square and 1 for a white square. I've got it working for a board where each square has a size of 1, but I can't work out how to make a scaleable version:

//Pseudo-code
checkerboardColour(Vec point)
{
return (floor(p.x) + floor(p.y)) % 2 == 0 ? white : black;
}

I know that I'd need to do a division of some sort to scale the size of the squares, but I can't work out where to put it. Say I wanted to quadruple the size of each black/white square, how would I insert a 'scale' variable into the function to make this happen?

Thanks!

Advertisement

Try this:

//Pseudo-code
checkerboardColour(Vec point, float fScale)
{
return ((int)(p.x/fScale) + (int)(p.y/fScale)) % 2 == 0 ? white : black;
}

Cool, that works :) I actually tried that first but I must have had a bad bracket or something...

Beware of negative numbers.

floor() rounds toward negative infinity, while casting to int rounds toward zero. Depending on how precise you are being with your language, both can be said to round "down".

In this case the two bits of code produce similar, but very different results. One of them will act as though it has a mirror along the axis, the other will be continuous. I'll let you figure out which to help re-enforce the importance.

edit: And since this is talking about the importance of differences is rounding, if you allow the processor to use the floating point round instruction (which is different than casting to int or using floor) then it will use banker's rounding --- that is, rounding toward the nearest even number. In many cases banker's rounding is better because it leads to less numeric drift. When people start talking about rounding to integers, it is best to clarify exactly what they mean; there are many options and each can give dramatically different results. The rounding most of us learned in school is: floor(x+0.5)

This topic is closed to new replies.

Advertisement