信不信由你,你可以做爲了統計這樣一個單一的隨機數。如果k
是隨機的值的數量,每一個在上述範圍內1..max_value
,則:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
int main(void)
{
int seed;
/*
* Grab a seed value from /dev/random to avoid time dependency
* artifacts in the first generated rand() value when running
* this multiple times in quick succession.
*/
FILE *fp = fopen("/dev/random", "r");
fread((char*)(&seed),sizeof(seed),1,fp);
fclose(fp);
srand(seed);
int k = 20;
int max_value = 20;
/*
* The k'th root of a single uniform has the same distribution as
* the max of k uniforms. Then use inversion to convert to desired
* output range.
*/
int num = 1 + max_value * exp(log(((double)rand())/RAND_MAX)/k);
printf("%d is the max of %d samples in the range 1..%d\n", num, k, max_value);
return 0;
}
具有相同的分佈範圍爲20項1..20隨機數的最大值,而無需循環!取決於多大的k
是多麼昂貴你的rand()
函數是,這真的可以得到回報。
來源
2013-11-02 18:45:39
pjs
它始終顯示相同的字符串編號。很奇怪。 –
這是爲什麼令人驚訝?如果你從1到20挑選20個隨機數,那麼很有可能(約64%)其中一個會是20個。每次發生時,它都會被選爲最大。 – Barmar
一個小調整:要得到1到20之間的數字,你需要'num = 1 + rand()* 20/RAND_MAX;' – pjs