返回一个随机偶数

4

我有以下几种方法。Rnd方法返回两个边界之间的一个随机整数:

  /* Create next batch of 55 random numbers */
  void advance_random (){
int j1;
double new_random;
for(j1=0; j1<24; j1++){
  new_random = oldrand[j1]-oldrand[j1+31];
  if(new_random<0.0){
    new_random = new_random+1.0;
  }
  oldrand[j1] = new_random;
}
for(j1=24; j1<55; j1++){
  new_random = oldrand[j1]-oldrand[j1-24];
  if(new_random<0.0){
    new_random = new_random+1.0;
  }
  oldrand[j1] = new_random;
}
 } //advance_ramdom

  /* Fetch a single random number between 0.0 and 1.0 */
  double randomperc(){
jrand++;
if(jrand>=55){
  jrand = 1;
  advance_random();
}
return((double)oldrand[jrand]);
  } //randomPerc

  /* Fetch a single random integer between low and high including the bounds */
  synchronized int rnd (int low, int high){
int res;
if (low >= high){
  res = low;
} else {
  res = low + (int)(randomperc()*(high-low+1));
  if (res > high){
    res = high;
  }
}
return (res);
  } // rnd

如何修改这个代码,使得返回的数字 mod2 = 0?

谢谢。


http://eternallyconfuzzled.com/arts/jsw_art_rand.aspx - sehe
5个回答

8

如果你想在范围[a, b]内获得一个随机数,那么你只需要在范围[(a+1)/2, b/2]内获得一个随机数,然后将其乘以2即可获得范围[a, b]内的随机偶数。


1
你需要将下限向上取整,否则在3和5之间的偶数会返回2。 2 * rnd((low+1)/2, high/2) - Peter Lawrey

5

使用 位掩码 强制最低有效位为零:

x = x & ~1;

2
请注意,在生成随机数之前,应先调整范围以确保随机分布。例如,如果范围为[2,4],则您将获得两倍于4的2。因此,您应该将范围扩展到[2,5],以获得2和4之间的随机分布。当然,对于非常大的范围,这变得可以忽略不计。如果范围是[3,n],则会得到一些超出范围的2。 - JB Nizet

2
最后,将代码运行结果乘以二——仍然是随机的,并且可以被二整除!

2
你需要注意溢出问题;具体来说,你应该减少原始随机数的范围。 - Oliver Charlesworth

1

使用以下代码如何:

return res & ~1;


0

在Java 1.7或更高版本中,我会使用ThreadLocalRandom

import java.util.concurrent.ThreadLocalRandom;

// Get even random number within range [min, max]
// Start with an even minimum and add random even number from the remaining range
public static int randEvenInt(int min, int max) {
    if (min % 2 != 0) ++min;
    return min + 2*ThreadLocalRandom.current().nextInt((max-min)/2+1);
}

// Get odd random number within range [min, max]
// Start with an odd minimum and add random even number from the remaining range
public static int randOddInt(int min, int max) {
    if (min % 2 == 0) ++min;
    return min + 2*ThreadLocalRandom.current().nextInt((max-min)/2+1);
}

使用ThreadLocalRandom的原因在这里解释了。另外,请注意,我们将输入+1到ThreadLocalRandom.nextInt()的原因是为了确保最大值包含在范围内。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接