2
generate(vec.begin(), vec.end(), [=](){return static_cast<T>(static_cast<double>(ran())
/RAND_MAX*(max-min)+min); });

问题:RAND_MAX*(max-min)+min);

好的,所以我知道这件事中的算法、lambda 表达式和捕获子句。我的问题对所有这些都很荒谬。上面加粗的文字是什么意思。我的意思是,我知道它是随机值生成过程的一部分。但不知道到底是怎么回事。所以有人可以分解那个微小的小代码。

4

5 回答 5

8

static_cast<double>(ran())/RAND_MAX*(max-min)+min);

我假设您输入错误rand(),它返回一个从 0 到 RAND_MAX 的伪随机整数。让我们以稍微澄清优先级的方式重写它:

(T) ( (((double) rand() / RAND_MAX) * (max-min) ) + min

所以它的作用是:

  1. rand(): take a random integer between 0 and RAND_MAX
  2. (double) / RAND_MAX: divide as double by RAND_MAX, yielding a uniformly distributed double between 0 and 1:
  3. * (max-min): multiply by the range (max-min), yielding a double from 0 to (max-min)
  4. +min: add the minimum to yield a random double between min and max
  5. static_cast<T>: cast it back to the original type

The result is a uniformly distributed random number of type T between min and max.

于 2012-05-11T03:48:58.793 回答
2

这是一个随机函数,其缺点是受限于 min(因为 rand 块可能返回零)并限制为 max,因为即使它返回 100% 的 max-min,并添加到 min,你也会达到最大值

于 2012-05-11T03:38:27.690 回答
2

该表达式static_cast<double>rand()/RAND_MAX创建一个介于 0.0 和 1.0 之间的数字,
当您将其乘以 时(max-min),您会更改范围,当您添加时,min您会移动范围。所以,在那个表达式之后,你有一个随机数(双精度),范围从minmax

于 2012-05-11T03:41:25.207 回答
2

您需要查看整个表达式:static_cast<double>(rand()) /RAND_MAX*(max-min)+min). 具有显式分组的看起来像:(static_cast<double>(rand()) /RAND_MAX)*(max-min)+min).
第一组返回一个介于 0 和 1 之间的随机值,因为rand()返回一个介于 0 到 RAND_MAX 之间的值。第二组将 0 到 1 范围转换minmax范围。

于 2012-05-11T03:43:55.270 回答
0

the ran() function returns a random value between min and max ?

but sometimes we need a random value between A and B (min and max). So we can adjust the result for it.

a is double, so we use a static_cast! 
a = rand()      ; 0     <=   a   <= RAND_MAX
a = a/RAND_MAX  ; 0     <=   a   <= 1
a = B * a       ; 0     <=   a   <= B
a = min +a      ; 0+min <=   a   <= B+min

to produce min <= a <= max,

B+min = max
B = max-min

in other hands

a = rand()/RAND_MAX*(max-min) + min

is a random number between min and max.

于 2012-05-11T03:55:24.640 回答