简体   繁体   English

是否可以在Mersenne Twister RNG(Java)中为nextInt指定上限和下限

[英]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). 我需要在Java / Kotlin(适用于Android)中生成随机数,尤其是使用Mersenne Twister算法。 I've tried using the Apache commons-math Mersenne Twister implementation which works great to generate random integers. 我尝试使用Apache Commons-math Mersenne Twister实现,该实现非常适合生成随机整数。 However I need to specify a fairly small range for these, the ints must be between 1 and 100. 但是,我需要为这些指定较小的范围,整数必须在1到100之间。

It doesn't seem to be possible to specify upper and lower bounds with the Apache implementation. 在Apache实现中似乎无法指定上限和下限。 Does anyone know of any alternative Mersenne Twister options for Java/Kotlin that accept bounds for the nextInt generated? 有人知道Java / Kotlin的其他替代Mersenne Twister选项可以接受生成的nextInt的范围吗?

AFAIK you can pass upper boundary of generated int to nextInt method, so it is possible to write simple extension function like that: 可以将生成的int的上边界传递给nextInt方法,因此可以编写如下简单的扩展函数:

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. 请注意,就像MT的nextInt结果不包括上限一样,因此如果您需要此行为,则可能需要在nextInt的参数中加1。

Also note that I did not test this function well, so do it yourself before using it. 另请注意,我对该功能的测试不够好,因此在使用前请自己进行测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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