我正在尝试实现这个我将用于值噪声的随机函数:
float random(int x, int y){
int r;
float s;
srand(y*hgrid+x+seed);
r=rand();
s = (float)(r & 0x7fff)/(float)0x7fff;
return (s);
}
正如此函数的作者所说 (https://code.google.com/p/fractalterraingeneration/wiki/Value_Noise):
It is important to note that some compilers have their own RNG, so this may not work for everyone. Visual C++ 2008 was especially troublesome, however GCC on Linux works perfectly.
所以我在windows上试了一下,用的是mingw。输出真的很奇怪,因为它给了我从 0.0 到 1.0 的增长数字。
在 Linux 上,它的工作方式与它应该的一样,从 0.0 到 1.0 的随机数。
因为我使用的是 mingw,它应该类似于 gcc,所以我期待以同样的方式工作。
为什么它不起作用?有没有办法让它发挥作用?
最佳答案
Why doesn't it works?
您每次都为随机数生成器重新设定种子,因此每个数字都是该种子值的简单函数。这似乎是我们想要的(这样您就可以为每个位置获得一致的值),但您不希望函数过于简单。
听起来 mingw 实现返回种子作为第一个生成的数字,而 linux 实现首先修改它。
Is there a way to make it works?
多次调用 rand
,以确保您不只是取回种子值。或者编写自己的计算,也许基于 common implementation of rand
unsigned r = y*hgrid+x+seed;
r = r * 1103515245 + 12345;
return (float)(r & 0x7fff)/(float)0x7fff;
关于c++ - 值噪声随机函数奇怪的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28352124/