[英]Rapid random number generating function in C
I'm trying to make a random number generator that produces many new random numbers very quickly. 我正在尝试使一个随机数生成器能够非常快速地生成许多新的随机数。 I have tried srand(time(NULL)) but since I'm trying to generate many number quickly this won't work.
我已经尝试过srand(time(NULL)),但是由于我试图快速生成许多数字,因此无法正常工作。 Next I tried this:
接下来,我尝试了这个:
int main()
{
seed_plus=time(NULL);
int i;
for (i=0; i<10;i++)
{
double R=ran(seed_plus);
printf("%lf\n",R);
seed_plus=seed_plus+1;
}
}
double ran (int seed_plus)
{
srand(seed_plus);
double random_number = (double)random()/(double)RAND_MAX;
return(random_number);
}
This works, but I would like to have "seed_plus=seed_plus+1" contained within the "ran" function. 这可行,但我想在“运行”函数中包含“ seed_plus = seed_plus + 1”。 When I move that statement inside the function I get many of the same "random" number, which leads me to believe that seed_plus is not being saved to memory since it is not the value being returned by the function?
当我在函数内移动该语句时,会得到许多相同的“随机”数,这使我相信seed_plus不会保存到内存中,因为它不是函数返回的值?
I'm pretty new to C, so any help would be appreciated! 我是C的新手,所以我们将不胜感激!
您只需要一次呼叫srand
,之后,所有对random
下一次呼叫将每次返回不同的号码。
There is no reason to seed the random number generator every time you need a random number. 每次需要随机数时,没有理由为随机数生成器提供种子。 Just simplify your code:
只需简化您的代码即可:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
double ran(void)
{
return (double)rand() / RAND_MAX;
}
int main(void)
{
srand(time(NULL));
for (int i = 0; i < 10; i++)
printf("%f\n", ran());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.