samedi 31 janvier 2015

Why does scala return a value out of range in this modulo operation?

This is a piece of code to generate random Long values within a given range, simplified for clarity:



def getLong(min: Long, max: Long): Long = {
if(min > max) {
throw new IncorrectBoundsException
}
val rangeSize = (max - min + 1L)
val randValue = math.abs(Random.nextLong())
val result = (randValue % (rangeSize)) + min
result
}


I know the results of this aren't uniform and this wouldn't work correctly for some values of min and max, but that's beside the point.


In the tests it turned out, that the following assertion isn't always true:



getLong(-1L, 1L) >= -1L


More specifically the returned value is -3. How is that even possible?





Aucun commentaire:

Enregistrer un commentaire