gpt4 book ai didi

c++ - 为什么 C++ 和 R 中的这些 RNG 不会产生相似的结果?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:07:47 25 4
gpt4 key购买 nike

请原谅这篇文章令人厌恶的菜鸟性质,但我有一个问题要问那些在个人计算机上使用 C++ 和 R 编程的人。

问题:为什么下面两个程序生成的随机数不相等,如何解决?

  1. 首先,我怀疑我误用了local函数和 <<- R程序中的运算符。
  2. 其次,我怀疑这可能是一个 float 精度问题。这两个程序有何不同对我来说并不是很明显,所以我不知道如何解决这个问题。

我已经尝试将我在 C++ 中的所有计算转换为 double/float (甚至 long double ),并使用 fmod而不是模运算符 % : 再次输出不同,但仍然与 R 中的输出不相似。我不知道它是否有任何重要意义,但我想补充一点,我正在使用 G++ 编译器编译 C++ 代码。

算法:以下算法可用于任何标准个人计算机。建议并行使用三个单词生成器,

  • mk = 171 mk-1 (mod 30269)
  • m'k = 172 m'k-1 (mod 30307)
  • m''k = 172 m''k-1 (mod 30323)

并将小数部分用作伪随机数

  • gk = {mk/30269 + m'k/30307 + m''k/30323}

我使用了初始值 m0 = 5、m'0 = 11 和 < em>m''0 = 17。

程序:我有以下 C++ 程序:

//: MC:Uniform.cpp
// Generate pseudo random numbers uniformly between 0 and 1
#include <iostream>
#include <math.h> // For using "fmod()"
using namespace std;

float uniform(){
// A sequence of initial values
static int x = 5;
static int y = 11;
static int z = 17;

// Some integer arithmetic required
x = 171 * (x % 177) - 2 * (x / 177);
y = 172 * (x % 176) - 35 * (y / 176);
z = 170 * (x % 178) - 63 * (z / 178);

/* If both operands are nonnegative then the
remainder is nonnegative; if not, the sign of
the remainder is implementation-defined. */
if(x < 0)
x = x + 30269;
if(y < 0)
y = y + 30307;
if(z < 0)
z = z + 30323;

return fmod(x / 30269. + y / 30307. + z / 30323., 1.);
}

int main(){
// Print 5 random numbers
for(int i = 0; i < 5; i++){
cout << uniform() << ", ";
}
}///:~

程序退出并输出以下代码:

0.686912, 0.329174, 0.689649, 0.753722, 0.209394,

我还有一个用 R 编写的程序,如下所示:

## Generate pseudo random numbers uniformly between 0 and 1
uniform <- local({
# A sequence of initial values
x = 5
y = 11
z = 17

# Use the <<- operator to make x, y and z local static
# variables in R.
f <- function(){
x <<- 171 * (x %% 177) - 2 * (x / 177)
y <<- 172 * (y %% 176) - 35 * (y / 176)
z <<- 170 * (z %% 178) - 63 * (z / 178)

return((x / 30269. + y / 30307. + z / 30323.)%%1.)
}
})

# Print 5 random numbers
for(i in 1:5){
print(uniform())
}

这个程序也退出并产生输出

[1] 0.1857093
[1] 0.7222047
[1] 0.05103441
[1] 0.7375034
[1] 0.2065817

如有任何建议,请提前致谢。

最佳答案

您的 R 代码中还需要一些 %/%(整数除法)。请记住,默认情况下,R 中的数字变量是 float ,而不是整数;所以 / 将使用非整数商进行普通除法。您还遗漏了处理负 x/y/z 的部分。

f <- function(){
x <<- 171 * (x %% 177) - 2 * (x %/% 177)
y <<- 172 * (y %% 176) - 35 * (y %/% 176)
z <<- 170 * (z %% 178) - 63 * (z %/% 178)

if(x < 0)
x <<- x + 30269;
if(y < 0)
y <<- y + 30307;
if(z < 0)
z <<- z + 30323;

return((x / 30269. + y / 30307. + z / 30323.)%%1)
}

进行这些更改后,结果似乎没有任何严重错误。 100000 次随机抽取的快速直方图看起来非常均匀,而且我找不到自相关性。仍然与您的 C++ 结果不匹配......

关于c++ - 为什么 C++ 和 R 中的这些 RNG 不会产生相似的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17681536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com