[英]rand() behaves differently between macOS and Linux
我正在嘗試使用 rand() 生成一個隨機數序列。 我有這樣的事情:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int Random(int min, int max)
{
/* returns a random integer in [min, max] */
double uniform; // random variable from uniform distribution of [0, 1]
int ret; // return value
srand((unsigned int)clock());
uniform = rand() / (double)RAND_MAX;
ret = (int)(uniform * (double)(max - min)) + min;
return ret;
}
int main(void)
{
for(int i=0; i<10; i++)
printf("%d ", Random(0, 100));
printf("\n");
return 0;
}
它在macOS v10.14 (Mojave) 和Ubuntu 18.04 (Bionic Beaver) 上執行時產生了不同的結果。
它適用於 Ubuntu:
76 42 13 49 85 7 43 28 15 1
但不是在 macOS 上:
1 1 1 1 1 1 1 1 1 1
為什么它在 macOS 上運行不佳? 隨機數生成器有什么不同嗎?
我是 Mac 用戶。 為了生成隨機數,我像這樣初始化種子:
srand(time(NULL));
另外,嘗試在你的 main.js 中初始化它。
如果您關心可重復的“隨機”數字,則應避免使用rand
函數。 即使種子是通過srand
給出的,C 標准也沒有准確指定rand
產生的序列是什么。 尤其:
rand
使用未指定的隨機數算法,該算法在 C 實現之間可能有所不同, 包括相同標准庫的版本。rand
返回值不大於RAND_MAX
,並且RAND_MAX
在 C 實現之間可能不同。相反,您應該使用具有已知算法的偽隨機數生成器的實現,並且您還應該依靠自己的方式將來自該算法的偽隨機數轉換為您想要的數字。 (例如,我為統一浮點數提供了這樣做的方法。請注意,當可重復性很重要時,還需要考慮其他事項。)
另請參閱以下內容:
rand
在 Mac 中已過時。 使用 random() 代替。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.