【问题标题】:stdlib.h rand() % range not from 0 to rangestdlib.h rand() % range not from 0 to range
【发布时间】:2013-12-16 13:03:13
【问题描述】:

我正在尝试从 C 中的数组中选择随机索引。The problem I'm having is that my random numbers aren't going from the range I expect (from 0 to 2047) as this example says that it will。仅仅从我得到的索引来看,我似乎得到了 1000-1200 之间的数字,而不是所需的范围。

这是调用 rand() 的代码。

#define MAXPAGES         2048    // maximum number of processes in the system

//until we have a node, pick random indexes.
while(node == NULL){
    table_index = rand() % MAXPAGES;
    node = table[table_index];
    if(node){
       fprintf(stderr, "%d\n", table_index);
       if(node->current_pages > 0) break;
       else node = NULL;
    }
}

我在 main 函数中只调用了一次 srand。

int main(int argc, char** argv) {
    int i;
    int simulations = 100000;
    // initialize the process hash table
    if(argc > 1){
        removal_algorithm  = atoi(argv[1]);
        if(argc == 3) simulations = atoi(argv[2]);
    }

    srand(time(NULL));
    for (i = 0; i < MAXPAGES; i++) table[i] = NULL;

    printf("Random replacement MMU simulation on %d simulations started\n", simulations);
    Simulate(simulations);
    printf("Random MMU simulation completed. only writing page faults:,");
    printf("%d, read / write page faults: %d, total page faults: %d\n", read_miss, write_miss, read_miss + write_miss);
}

示例序列。

 1117
 1069
 1103
 1118
 1071
 1117
 1120
 1092
 1099
 1116
 1121
 1122
 1110
 1116
 1069
 1113
 1120
 1117
 1116
 1071
 1121
 1094
 1110
 1119
 1102
 1117
 1071
 1108
 1102
 1099
 1109
 1109
 1092
 1109
 1120
 1108
 1094
 1101
 1122
 1086
 1110
 1108
 1119
 1120
 1092
 1113
 1117
 1121

【问题讨论】:

  • 这似乎不是问题所在,但请注意,rand() % SOME_VALUE 可能会因RAND_MAXSOME_VALUE 的值而产生很大偏差。如果RAND_MAX不是SOME_VALUE的倍数,请考虑生成的分布。
  • 如何在不使用 mod 运算符的情况下获得随机范围?

标签: c random


【解决方案1】:

您的代码显然只打印那些table[table_index] 不为空的索引。如果table[0] 为空,它将永远不会打印0。 IE。此代码不一定演示rand() 的行为。相反,它的行为可能主要由table 的内容决定。

【讨论】:

  • 啊,废话。这意味着我的表格分布不正确。好吧,我很高兴我至少现在抓住了这个。
猜你喜欢
  • 2020-11-14
  • 2022-12-19
  • 2022-12-02
  • 1970-01-01
  • 1970-01-01
  • 2020-09-05
  • 1970-01-01
  • 2011-12-22
  • 2016-05-02
相关资源
最近更新 更多