a[] :
0 | 1 | 2 | 3 |
|
0.1 | 0.2 | 0.3 | 0.4 |
|
cumsums[]:(cumsums[i]表示返回值小于i的概率)
0 | 1 | 2 | 3 | 4 |
0.0 | 0.1 | 0.3 | 0.6 | 1.0 |
static double cumsums[];
void GetCumsums(double a[],double cumsums[],int length) (length=5)
{
cumsums[0] = 0.0;
for(int index = 1;index < length;index++)
{
cumsums[index] = cumsums[index - 1] + a[index - 1];
}
}
int Discrete(double cumsums[],int length)
{
double probability = ((double)rand()) / RAND_MAX;
int low = 0;
int high = length - 1;
int middle;
while(low + 1 < high)
{
middle = (low + high) / 2;
if(cumsums[middle] < probability)
{
low = middle;
}
else
{
high = middle;
}
}
return low;