We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I would like to create a simple gradient over a 300 x 300 (or whatever size) square. My idea was to use the HSB color mode, and to use Cantor's pairing function (https://en.wikipedia.org/wiki/Pairing_function#Cantor_pairing_function) to map each coordinate pair (x, y) on the grid to a unique hue. So the H in the triple (H, S, B)
will be given by the formula printed below - and cantor(x, y)
and cantor(a, b)
will never be equal when x != a
or y!= b
, as per the properties of Cantor's pairing function.
H = cantor(x, y) = (1/2) * (x + y) * (x + y + 1) + y
As you can see, I have changed the colorMode
to allow for the largest possible value that can be generated by the pairing function (that is, when i = width
, j = height
).
The code is the following:
float cantormax;
void setup() {
size(300, 300);
noLoop();
float cantormax = (1/2) * (width + height) * (width + height + 1) + height;
colorMode(HSB, cantormax, 255, 255);
}
void draw() {
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
float cantor = (1/2) * (i + j) * (i + j + 1) + j;
stroke(cantor, 200, 200);
point(i, j);
}
}
}
Now, the output is a nice gradient to be sure, but the horizontal bands have the same hue value, apparently! This can be confirmed by printing all of the values of cantor to the console - there are tons of repeats in the for loop.
Why is my idea not working? I know there are much easier ways to specify such a background of colors, but I liked this idea.
Answers
Replace 1/2 with .5 to avoid integer division problems?
I didn't know that problems occurred with integer division? Thanks for your suggestion - now it gives me a sort of diagonal gradient, but with a massive patch of red covering most of the screen!
did you change it on line 6 and 14?
looks ok here if i do both. looks very red if i only change line 14...
That did it - thanks! Though I'm not sure why the colors are not different everywhere over the output.