我需要在指定的时间间隔内生成随机数,[max; min].
此外,随机数应该在区间上均匀分布,而不是位于特定点.
Currenly我正在生成:
for(int i=0; i<6; i++)
{
DWORD random = rand()%(max-min+1) + min;
}
Run Code Online (Sandbox Code Playgroud)
从我的测试中,只有一点产生随机数.
Example
min = 3604607;
max = 7654607;
Run Code Online (Sandbox Code Playgroud)
随机数生成:
3631594
3609293
3630000
3628441
3636376
3621404
Run Code Online (Sandbox Code Playgroud)
从下面的答案:好的,RAND_MAX是32767.我在C++ Windows平台上.有没有其他方法来生成具有均匀分布的随机数?
在我们需要生成概率的情况下,例如具有 75% 的抛头和 25% 的抛尾的偏置硬币。按照惯例,我会这样做:
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int heads=0, tails=0;
srand(time(NULL));
number = rand() % 100 + 1; //Generate random number 1 to 100
if (number <= 75) //75% chance
heads++; //This is head
else
tails++; //This is tail
}
Run Code Online (Sandbox Code Playgroud)
这是一个可以运行的代码,但是当我为另一个用户回答关于偏置币的类似问题时,一些用户提到了 100 的倍数。由于随机函数生成均匀分布,我觉得上面的代码已经足够了用于模拟概率事件。
在过去的 SO 帖子中,用户 Bathsheba 提到了一些关于 100 的倍数的内容:用偏置硬币模拟抛硬币的程序 我想知道我的代码中与此相关的可能问题是什么。
我的问题是:上面的代码是一个可接受的代码来创建一个概率模拟吗?或者这些代码中是否有任何缺陷会影响模拟结果的准确性。如果上述代码有缺陷,那么实现概率模拟的正确方法是什么?
编辑:通过 10,000,000 次抛掷的模拟测试。它总是以大约 75.01%-75.07% 的概率产生抛头。那么当它生成看似准确的结果时会出现什么问题。(生成的结果似乎没有倾斜)
我需要实现一个好的RNG,我猜Mersenne Twister可能对我有好处.我没有找到任何可行的C++实现,我是一个糟糕的谷歌搜索者还是真的不容易找到?!我以前尝试过rand()
:
srand((unsigned)time(0));
for (int i = 0; i < 9; i++) {
random = rand();
cout<<random;
}
Run Code Online (Sandbox Code Playgroud)
我不知道为什么,但随机变量总是相同的数字.....但是如果我添加一个Sleep(1000)
,它的工作原理!像这样:
srand((unsigned)time(0));
for (int i = 0; i < 9; i++) {
random = rand();
cout<<random;
Sleep(1000);
}
Run Code Online (Sandbox Code Playgroud)
所以我决定尝试Mersenne Twister ......有人能找到一个解决方案(因为我需要找到非常大量的随机数,所以我不能使用Sleep(1000)
,这需要时代!)或者帮助我实现Mersenne Twister或者也许是另一个好的RNG.谢谢,抱歉我的英语不好......
当我打电话时,我目前正在收到分段故障(分段故障:11)newUnitID()
.
不知道我做错了什么.
这是我的头文件,其函数是:
#include <iostream>
#include <cstring>
#include <string>
#include <cstdlib>
#include <ctime>
#include <vector>
#ifndef UnitManager
#define UnitManager
using namespace std;
char randomIDChar(){
static const char alphanum[] =
"0123456789"
"!@#$%^&*"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
int stringLength = sizeof(alphanum) - 1;
srand(time(0));
for(int z=0; z < 21; z++)
{
return alphanum[rand() % stringLength];
}
return 1;
}
string newUnitID(){
vector<char> v;
for(int i=0; i < 50; i++){
v[i] = randomIDChar();
}
string str(v.begin(),v.end());
return str;
}
#endif
Run Code Online (Sandbox Code Playgroud) c++ ×4
random ×4
algorithm ×1
c ×1
ipad ×1
math ×1
objective-c ×1
probability ×1
stdstring ×1
string ×1