Question about floor division and mod. My mental m...
# getting-started
r
Question about floor division and mod. My mental model is basically splitting the number line into chunks of a given size.
``mod``
tells you how far into a chunk you are, and
``floorDiv``
tells you which chunk you are in. Is getting the start of the given chunk as simple as
``floorDiv * chunkSize``
? Is it more complicated than that? Is my mental model fundamentally wrong?
e
div is to rem as floorDiv is to floorMod
in other words, they come in pairs; mod & floorDiv are not from the same pair
r
For context, I have the following functions that I use for a project:
Copy code
``````fun offsetInChunk(x: Int, size: Int, origin: Int = 0): Int =
((x - origin) % size + size) % size
fun startOfChunk(x: Int, size: Int, origin: Int = 0): Int =
x - offsetInChunk(x, size, origin)
fun indexOfChunk(x: Int, size: Int, origin: Int = 0): Int =
(startOfChunk(x, size, origin) - origin) / size``````
And I'm wondering if it makes sense to replace them with:
Copy code
``````fun offsetInChunk(x: Int, size: Int, origin: Int = 0): Int =
(x - origin).mod(size)
fun startOfChunk(x: Int, size: Int, origin: Int = 0): Int =
indexOfChunk(x, size, origin) * size
fun indexOfChunk(x: Int, size: Int, origin: Int = 0): Int =
(x - origin).floorDiv(size)``````
e
for all x and non-zero y, x == x / y * y + x % y (aka x == x.div(y) * y + x.rem(y)) x == floorDiv(x, y) * y + floorMod(x, y)
r
@ephemient 1.5.0 introduced
``floorDiv``
and
``mod``
, no
``floorMod``
e
@Ruckus I was referring to java.lang.Math.floorMod&floorDiv. I haven't checked if Kotlin's new operators line up with those.
r
Ah, in that case, I believe Java's
``floorMod``
is equivalant to Kotlin's
``mod``
, but I believe they are implemented differently.
e
looks like they do, although the naming is unfortunate
IMO everything should have been named div/mod and quot/rem from the start, but it's too late now
r
That makes sense. As far as my original question goes (assuming
``floorMod``
in place of
``mod``
), does my mental model hold, and is the replacement for my code valid, or am I off somewhere? In testing the math seems to work out, but my mental model somewhat breaks down with the concept of negative sizes, so I was wondering if it was still valid with the appropriate extension into the negatives, or is it a fundamentally invalid model that happens to line up with the math under certain circumstances?
e
if you're working on positive numbers only, then none of it matters, both sets of operators have the same result 🙂
the difference is that Java's (and Kotlin's) x % y keeps the sign of x, while floorMod(x, y) keeps the sign of y. the result of x / y and floorDiv(x, y) are consistent with that to maintain the previous invariant