rand()真的可以这么糟糕吗? [英] Can rand() really be this bad?
问题描述
以上是使用rand()获取随机坐标并在这些坐标处的像素值上添加常量的示例图像.这是经过数千次迭代后的样子.我正在Mac OS X Lion中使用stdlib.h中的rand(),并给它time(NULL)作为种子.
Above is an example image generated by using rand() to get random coordinates and add a constant to the pixel value at those coordinates. This is how it looks from a few thousand iterations. I'm using the rand() from stdlib.h in Mac OS X Lion, giving it time(NULL) as the seed.
您可以清楚地看到垂直线,好像具有x坐标奇数的竖线比具有x偶数坐标的竖线更高.
You can clearly see the vertical lines, as if the ones with an odd x-coordinate have higher values than those with even x-coordinates.
我将如何实现更好的算法,或者在哪里可以找到没有很多依赖性的算法呢? (我希望使用仅标头文件).
How would I implement a better algorithm, or where can I find one that doesn't have many dependencies? (I would prefer a header-only file).
这是代码(很抱歉,我花了这么长时间):
Here's the code (sorry it took me so long):
void generate(int iterations = 1) {
for (unsigned int x = 0;x < (area * 4);++x) {
map[rand() % area] += 1;
}
number a = min();
number b = max();
for (int i = 0;i < area;++i) {
map[i] -= a;
map[i] /= b;
}
}
地图包含双精度浮点数,后来又变成了RGB值.
Map contains double-floats and is later turned into RGB values.
推荐答案
Have you tried arc4random()
? It provides much stronger and more uniform random values than rand()
.
您还可以尝试 SecRandomCopyBytes()
,它是Security.framework的一部分.这基本上只是从/dev/random中读取.
You could also try SecRandomCopyBytes()
, which is part of Security.framework. This basically just reads from /dev/random.
这篇关于rand()真的可以这么糟糕吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!