不平衡随机数发生器 [英] Unbalanced random number generator

查看:23
本文介绍了不平衡随机数发生器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须从升序数组中选取一个元素.较小的元素被认为更好.所以如果我从数组的开头选择一个元素,它被认为是一个更好的选择.但与此同时,我不希望选择是确定性的并且始终是相同的元素.所以我在寻找

I have to pick an element from an ascending array. Smaller elements are considered better. So if I pick an element from the beginning of the array it's considered a better choice. But at the same time I don't want the choice to be deterministic and always the same element. So I'm looking for

一个随机数生成器,生成范围为 [0, n] 的数字,但是数字越小,产生的机会就越大.

a random numbers generator that produces numbers in range [0, n], but the smaller the number is, the more chance of it being produced.

我想到了这一点:

num = n;
while(/*the more iteration the more chance for smaller numbers*/)
  num = rand()%num;

我想知道是否有人有更好的解决方案.
我确实看过一些类似的问题,但他们通常有关于随机数生成的详细信息.我正在寻找这种特定类型的随机数生成的解决方案,无论是算法还是提供它的库.

I was wondering if anyone had a better solution.
I did look at some similar questions but they have details about random number generation generally. I'm looking for a solution to this specific type of random number generation, either an algorithm or a library that provides it.

推荐答案

Generate a Random number, say x, between [0,n) 然后再生成另一个Random浮点数,比如 y,在 [0,1] 之间.然后将 x 乘以 y 的幂并使用 floor 函数,您将得到您的号码.

Generate a Random number, say x, between [0,n) and then generate another Random floating point number, say y, between [0,1]. Then raise x to the power of y and use floor function, you'll get your number.

int cust(int n)
{
  int x;
  double y, temp;
  x = rand() % n;
  y = (double)rand()/(double)RAND_MAX;
  temp = pow((double) x, y);
  temp = floor(temp);
  return (int)temp;
}

更新:以下是调用上述函数 10 次的一些示例结果,n = 10、20 和 30.

Update: Here are some sample results of calling the above function 10 times, with n = 10, 20 and 30.

2 5 1 0 1 0 1 4 1 0

1 2 4 1 1 2 3 5 17 6

1 19 2 1 2 20 5 1 6 6

这篇关于不平衡随机数发生器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆