Skip to content

Instantly share code, notes, and snippets.

@Jimbly
Created October 20, 2020 20:19
Show Gist options
  • Save Jimbly/72ef83ef1467701316b6c8165573bf3f to your computer and use it in GitHub Desktop.
Save Jimbly/72ef83ef1467701316b6c8165573bf3f to your computer and use it in GitHub Desktop.
const { round, floor, ceil } = Math;
let correct = [0,0,0];
function test(dpr, dim) {
let clientWidth = round(dim / dpr);
let scaled = clientWidth * dpr;
if (round(scaled) === dim) {
correct[0]++;
}
if (floor(scaled) === dim) {
correct[1]++;
}
if (ceil(scaled) === dim) {
correct[2]++;
}
}
function testWidths(widths) {
let weighted_correct = [0,0,0];
let weighted_total = 0;
// from https://arh.antoinevastel.com/reports/stats/deviceType_screen-devicePixelRatio_report.html
[
[1, 0.8888888955116272],
[8, 0.8955223880597015],
[5, 0.8999999761581421],
[1, 0.9599999785423279],
[1, 0.8500000238418579],
[5, 1.125],
[1, 1.7647058823529411],
[2, 1.7999999523162842],
[176, 1.5],
[362, 1.25],
[1, 1.7000000476837158],
[1, 1.700084924697876],
[4, 1.3043478260869565],
[1, 1.399999976158142],
[1, 1.3953488372093024],
[2, 1.3333333333333333],
[1, 1.1145833730697632],
[2, 1.375],
[1, 1.1041666269302368],
[14, 1.100000023841858],
[5, 1.5625],
// [7615, 1],
[3, 1.2999999523162842],
[2, 1.600000023841858],
[2, 1.5789473684210527],
[5, 1.2],
[1, 1.3312500715255737],
[22, 1.75],
[3, 2.2222222222222223],
[1, 2.25],
[4, 2.608695652173913],
[25, 2.75],
// [1284, 2],
[2, 2.1000001430511475],
[12, 2.549999952316284],
[1, 2.1875],
[15, 2.5],
[1, 2.0001001358032227],
[1, 2.3375000953674316],
[47 , 2.625],
// [208, 3],
[19, 3.5],
[2, 3.4000000953674316],
// [33, 4],
].forEach((pair) => {
let [count, dpr] = pair;
widths.forEach(test.bind(null, dpr));
for (let ii = 0; ii < correct.length; ++ii) {
weighted_correct[ii] += correct[ii] / widths.length * count;
correct[ii] = 0;
}
weighted_total += count;
});
let labels = ['Math.round', 'Math.floor', 'Math.ceil'];
console.log(weighted_correct.map((a, idx)=>labels[idx] + ': ' + (100*a / weighted_total).toFixed(1)).join('\n'));
}
let widths = [];
for (let ii = 1; ii < 1000; ++ii) {
widths.push(ii);
}
testWidths(widths);
console.log('');
testWidths([480, 640, 768, 800, 1024, 1080, 1280, 1920, 2560, 3840]);
All resolutions:
Math.round: 69.1
Math.floor: 56.8
Math.ceil: 56.6
Common resolutions only:
Math.round: 80.9
Math.floor: 70.6
Math.ceil: 76.3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment