Sign in to follow this  

Checkerboard algorithm?

This topic is 1426 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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!

 

Share this post


Link to post
Share on other sites

Try this:

 

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

Share this post


Link to post
Share on other sites
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) Edited by frob

Share this post


Link to post
Share on other sites

This topic is 1426 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this