downscale icon indicating copy to clipboard operation
downscale copied to clipboard

`(value + 0.5) << 0` might actually be slightly faster, and is more accurate

Open jeffpeck10x opened this issue 3 years ago • 1 comments

For the round function, I noticed that you use 0.49, which seems to give a speed boost in some circumstances, but with random numbers, apparently not.

function createRandom(count, scale) {
  const a = new Float64Array(count);
  for (let i = 0; i < count; i++) {
    a[i] = Math.random() * scale;
  }
  return a;
}

function roundA(a, b) {
  for (let i = 0; i < a.length; i++) {
    b[i] = (a[i] + 0.49) << 0;
  }
}

function roundB(a, b) {
  for (let i = 0; i < a.length; i++) {
    b[i] = (a[i] + 0.5) << 0;
  }
}

function trunc(a, b) {
  for (let i = 0; i < a.length; i++) {
    b[i] = a[i] << 0;
  }
}

function main() {
  const a = createRandom(100000000, 1000);
  const b = new Int32Array(a.length);
  console.time("roundA");
  roundA(a, b);
  console.timeEnd("roundA");
  console.time("roundB");
  roundB(a, b);
  console.timeEnd("roundB");
  console.time("trunc");
  trunc(a, b);
  console.timeEnd("trunc");
  console.time("roundA");
  roundA(a, b);
  console.timeEnd("roundA");
  console.time("roundB");
  roundB(a, b);
  console.timeEnd("roundB");
  console.time("trunc");
  trunc(a, b);
  console.timeEnd("trunc");
}

main();
roundA: 301.97607421875 ms
roundB: 184.259033203125 ms
trunc: 179.185791015625 ms
roundA: 177.18603515625 ms
roundB: 179.783935546875 ms
trunc: 178.2119140625 ms

jeffpeck10x avatar Oct 14 '21 22:10 jeffpeck10x

Sure thing! I picked .49 value to increase an accuracy:

assuming that input value range:

  • from 0.0 to 0.5 should result 0
  • from 0.51 to 1 should result 1

This will still give inacurate result for input value 0.501, but in context of color value - slight color shift might not be noticable

ytiurin avatar Oct 17 '21 21:10 ytiurin