简体   繁体   中英

Is it possible to specify the upper and lower bounds for nextInt in Mersenne Twister RNG (Java)

I have a requirement to generate random numbers, specifically using the Mersenne Twister algorithm, in either Java/Kotlin (for Android). I've tried using the Apache commons-math Mersenne Twister implementation which works great to generate random integers. However I need to specify a fairly small range for these, the ints must be between 1 and 100.

It doesn't seem to be possible to specify upper and lower bounds with the Apache implementation. Does anyone know of any alternative Mersenne Twister options for Java/Kotlin that accept bounds for the nextInt generated?

AFAIK you can pass upper boundary of generated int to nextInt method, so it is possible to write simple extension function like that:

fun MersenneTwister.nextInt(min: Int, max: Int) = min + nextInt(max - min)

Please note that like MT's nextInt result does not include upper boundary, so you might want to add 1 to nextInt's argument if you need this behavior.

Also note that I did not test this function well, so do it yourself before using it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM