在C++中,如何在-10到10的区间内产生随机数?C++中从-10到10的随机数
srand(int(time(0)));//seed
for(int i = 0; i < size; i++){
myArray[i] = 1 + rand() % 20 - 10;//this will give from -9 to 10
myArray2[i] =rand() % 20 - 10;//and this will -10 to 9
}
在C++中,如何在-10到10的区间内产生随机数?C++中从-10到10的随机数
srand(int(time(0)));//seed
for(int i = 0; i < size; i++){
myArray[i] = 1 + rand() % 20 - 10;//this will give from -9 to 10
myArray2[i] =rand() % 20 - 10;//and this will -10 to 9
}
你需要一系列的21,而不是20,所以做这样的事情:
x = rand() % 21 - 10;
只是为了增加这个...原因是实际上有21种可能性......数出来。包括0。 – mpen 2010-04-19 07:54:52
请注意,使用朴素模数会偏向较小的数字。如果你需要一致性,那么你需要拒绝一些数字'rand()'返回。 – Joey 2010-04-19 08:00:03
rand()从0..RAND_MAX生成数字,其中RAND_MAX与库相关,但必须至少为32767.如果RAND_MAX%21!= 0,则获得特定数字的概率更高。在大多数实际应用中,这并不重要,但在某些科学计算中,这可能会严重影响计算结果。 – zoli2k 2010-04-19 08:03:58
你有一个fencepost错误 - 你感兴趣的范围是比你使用的模大一个;而不是尝试:
myArray2[i] =rand() % 21 - 10;//and this will -10 to +10
不知道为什么这会吸引匿名downvote? – 2013-09-07 18:23:37
rand() % 21 - 10
如果你想要的数字是在范围[ - 10,10],那么你有21个可能的数字。
(rand() % 21) - 10;
可以使用rand() % 21
产生[0,20]
之间的随机数,然后从每一个生成的号码减去10
。
(rand()%21) - 10; ?
或者我在这里错过了什么?
使用Boost Random Number Library。内置的随机数发生器具有非常差的分配质量。此外,boost还为您提供了许多有用的生成器。
// based on boost random_demo.cpp profane demo
#include <iostream>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int.hpp>
#include <boost/random/variate_generator.hpp>
int main() {
boost::mt19937 gen(42u); // seed generator
boost::uniform_int<> uni_dist(-10, 10); // random int from -10 to 10 inclusive
boost::variate_generator<boost::mt19937&, boost::uniform_int<> >
uni(gen, uni_dist); // callable
for(int i = 0; i < 10; i++)
std::cout << uni() << ' ';
}
输出:从未来
-3 6 9 -7 5 6 2 2 -7 -1
注:这是built-in in C++11现在。
+1。它甚至为您提供了一个从一个范围内生成一个数字的函数。没有所有这种做错的麻烦:-) – Joey 2010-04-19 09:05:30
为了得到均匀分布,你必须把使用RAND_MAX
第一
static_cast<int>(21*static_cast<double>(rand())/(RAND_MAX+1)) - 10
rand() % 21 - 10;
更快,往往是在应用中使用,但所得到的分布并不均匀,。函数rand()
生成从0
到RAND_MAX
的数字。如果RAND_MAX%21!=0
较低的数字以较高的概率生成。
您也可以考虑使用模方法,但用一些随机数滴:
int randMax = RAND_MAX - RAND_MAX%21;
int p=RAND_MAX+1;
while(p>randMax)
p=rand();
x=p%21 - 10;
编辑(由约翰和史蒂夫评论):
当RAND_MAX
有分裂是来自范围内的一些数字,这些数字将被更频繁地选择,因此正确的处理方式是拒绝将导致目标区间上的不均匀分布的数字。
使用Boost随机库(由Danvil提到),随机数均匀性的所有问题都被消除了。
使用这将工作:
int x = (rand() % 21) - 10;
cout<<x;
你可以使用Knuth的消减随机数发生器产生在(0,1)数字,“U”,然后使用这个简单的线性方程得到在[-10,10]的随机数:
-10*u + (1-u)*10
使用C++ 11的random
库,这是更简单,更不容易出错(见rand() Considered Harmful presentation和slides更多详情)。下面的示例在间隔[-10,10]
中生成数字:
#include <iostream>
#include <random>
int main()
{
std::random_device rd;
std::mt19937 e2(rd());
std::uniform_int_distribution<int> dist(-10, 10);
for (int n = 0; n < 10; ++n) {
std::cout << dist(e2) << ", " ;
}
std::cout << std::endl ;
}
在C++ 11中,您希望使用''库。 –
bames53
2012-10-12 17:26:56
@ bames53同意我使用'std :: uniform_int_distribution'就像我在我的回答中做的那样更有意义,尤其是考虑到[rand()Considered Harmful](http://channel9.msdn.com/Events/GoingNative/2013/rand-认为有害)。 – 2013-09-09 01:54:53