c++ - 值噪声随机函数奇怪的输出

标签 c++ c gcc random mingw

我正在尝试实现这个我将用于值噪声的随机函数:

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/

相关文章:

c++ - 如何将菜单栏添加到 QWidget?

c++ - Linux 上哪些 C++ IDE 的 "intellisense"与 Visual Studio 相当或更好?

c++ - 多次从第一行读取文本文件(C++)

c -++在指针中的不同用法

c - 为什么我的程序不能运行?

c++ - 二进制快速排序起始位位置

c - scanf ("%s")、sscanf ("%s") 和 scanf ("%s ") 之间有什么区别?

c++ - GCC 中默认参数段错误的 std::map 参数和空括号初始化器

无法在mac上执行C代码(最初在DevC++中执行)

c++ - 通过转换第一个字段来安全访问父类