「Processing」「P5.js」Matrix arrangement calculation difference

The same calculation method gets different results in 「processing」 and 「P5.js」.

Processing:

int total;
float itemSize;

void setup() {
  size(400, 400);

  total = 6;
  itemSize = width/total;
}

void draw() {
  clear();

  for (int i = 0; i < sq(total); i ++) {
    float x = i % total * itemSize + itemSize/2;
    float y = i / total * itemSize + itemSize/2;
    fill(-1);
    circle(x, y, 30);
  }
}

Result:

P5.js

let total;
let itemSize;

function setup() {
  createCanvas(400, 400);

  total = 6;
  itemSize = width / total;
}

function draw() {
  background(220);

  for (let i = 0; i < sq(total); i++) {
    let x = i % total * itemSize + itemSize / 2;
    let y = i / total * itemSize + itemSize / 2;

    circle(x, y, 30);
  }
}

Result:

I think the problem may appear in the “integer” and “floating point” issues, but it still can’t be solved after adjusting on P5.js.

Why does this happen? Very grateful for your help!

1 Like

In p5.js (JavaScript) numbers are all floats. So i / total can take value like 0.5 (when i is 3, for example)

However in processing, because you are using int, the result above will be 0 instead of 0.

You can use floor(i / total) to fix it in p5.js.

1 Like

@micuat The problem was solved smoothly with your help, thank you very much!

This is the adjustment I made:

let total;
let itemSize;

function setup() {
  createCanvas(400, 400);

  total = 6;
  itemSize = width / total;
}

function draw() {
  background(220);

  for (let i = 0; i < sq(total); i++) {
    let x = floor(i % total) * itemSize + itemSize / 2;
    let y = floor(i / total) * itemSize + itemSize / 2;

    circle(x, y, 30);
  }
}
1 Like