Is there a more efficient way than `round(number /...
# getting-started
a
Is there a more efficient way than
round(number / length) * length
to round a number by a length ?
m
is it rounding for output only? Than I suggest using
Copy code
"%.${length}f".format(number)
otherwise, mathmatically theres is not really much you can do to round more efficiently
k
The print formatting is not equivalent to the OP's rounding (which means to round to the nearest multiple of
length
). I think, if
length
is an integer, you can probably make it slightly more efficient using just integer arithmetic, but it's probably not worth the effort.
a
Yes it's integer, but it's an operation that will be used at least 300 times per second, it's for a Kotlin/JS game
k
If it's for JS, I wouldn't bother, as there is no integer type in Javascript; only Number.
t
If you can guarantee length is a multiple of 2, you can use bitwise operators to round your number to a multiple of length
@Ayfri for example if you want to round by 8, shift right 3 and then shift left 3 (8 = 2^3)
That why for example, Minecraft, uses a lot of 8's and 16's as their grid size, because it makes the frequent rounding to snap to a grid much more efficient.
technically, if you’re going to shift right/left 3 you can just use bitwise & to delete the last 3 bits
For example, in JS
Copy code
const numberToRound = 15; 
const length = 8
const bitmask = Number.MAX_SAFE_INTEGER - length + 1;

console.log(numberToRound & bitmask);
But again, only works for multiples of 2
Make sure to test the performance though, I’m not sure if JavaScript’s representing all numbers in floating point makes this optimization useless or not. I know it works on platforms that have true integer types.