c++ - 生成 4 个方向随机游动的 RCPP 函数

标签 c++ r math rcpp

我正在尝试生成一个名为 StepstoShop 的函数,它将生成一个 n*2 矩阵,表示 x 和 y 坐标。允许的方向只有北、南、东和西(不允许对角线移动)

这是我到目前为止开发的代码

#include <RcppArmadilloExtensions/sample.h>
#include <cstdlib>
#include <ctime>
using namespace Rcpp;

// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]


NumericMatrix StepstoShop(double Steps){

    NumericMatrix SampleGen(Steps,2);
    int n=SampleGen.size();
    int colnum= rand()%1;



for( int i=0; i<n; i++)
      { SampleGen(i,colnum)=(rand()%3)-1;
      }

return SampleGen;
}

我试图通过行在 for 循环中将 0 和 1 之间的随机数分配索引到列,以获得 4 个方向的期望结果 (0,1) (1,0) (-1,0) (0,-1),但是我得到了 8 个方向的混合物。

任何指导,将不胜感激

谢谢

我回顾性地包含了 R 代码来说明我试图重新创建的内容

  # compute path
  n <- 1000
  rw <- matrix(0, ncol = 2, nrow = n)
  # generate the indices to set the deltas
  indx <- cbind(seq(n), sample(c(1, 2), n, TRUE))

  # now set the values
  rw[indx] <- sample(c(-1, 1), n, TRUE)
  # cumsum the columns
  rw[,1] <- cumsum(rw[, 1])
  rw[, 2] <- cumsum(rw[, 2])

  plot(0,type="n",xlab="x",ylab="y",main="Random Walk Simulation In Two 
  Dimensions",col=1:10,xlim=range(-10,15),ylim=range(-40,40))

  # use 'segments' to color each path
  segments(head(rw[, 1], -1)
  , head(rw[, 2], -1)
  , tail(rw[, 1], -1)
  , tail(rw[, 2], -1)
  , col = rainbow(nrow(rw) -1)  # a range of colors
  )

  end<-cbind(-10,30)
  start<-cbind(0,0)

  points(start,pch=16,col="green", cex = 3)
  points(end,pch=16,col="red", cex = 3)

思路是将这段代码迭代10万次,计算到达终点的概率

谢谢

最佳答案

我会用

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
IntegerMatrix StepstoShop(double Steps){

  IntegerVector possible_x = IntegerVector::create(0, 1, -1, 0);
  IntegerVector possible_y = IntegerVector::create(1, 0, 0, -1);
  IntegerMatrix SampleGen(Steps, 2);
  int ind;

  for (int i = 0; i < Steps; i++) {
    ind = R::runif(0, 4);
    SampleGen(i, 0) = possible_x[ind];
    SampleGen(i, 1) = possible_y[ind];
  }

  return SampleGen;
}

关于c++ - 生成 4 个方向随机游动的 RCPP 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51950067/

相关文章:

c++ - std::function 重载有类似的转换

c++ - 两个序列与 STL 的匹配数

c++ - 余弦/正弦矩阵数学

c++ - 在 C++ 中匹配俄语元音

r - 从网站提取 .csv 文件

从 R 中的列表中删除 ""元素

r - for循环R中的样本

C 程序使用函数将 float 四舍五入到小数点后 3 位?

algorithm - 如何快速找到空间区域中的点

java - Android向圆弧边缘添加线标记