简体   繁体   English

如何循环数组并将操作值存储在其他数组中

[英]How to loop over array and store values of operations in other array

in order to draw a schema (Approximation error, Sample size) I would like to loop over an array (runs) to get 4 values of approximation errors, when I try with one value it's working:为了绘制一个模式(近似错误,样本大小),我想循环一个数组(运行)以获得 4 个近似错误值,当我尝试使用一个值时它正在工作:

在此处输入图像描述

But when I start using an array I can print that values but I can't store the result in one variable in order to have them all values stored in all variables like runs to display them in the plot, here's my code:但是当我开始使用数组时,我可以打印这些值,但我不能将结果存储在一个变量中,以便将所有值存储在所有变量中,例如运行以在 plot 中显示它们,这是我的代码:

runs <- c(1000, 10000, 100000, 1000000)
apro_err <- c()
pi_real <- 3.14159265

for (i in runs){
  #runif samples from a uniform distribution
  xs <- runif(i,min=-0.5,max=0.5)
  ys <- runif(i,min=-0.5,max=0.5)
  in.circle <- xs^2 + ys^2 <= 0.5^2
  mc.pi <- (sum(in.circle)/i)*4
  absdif <- abs(mc.pi - pi_real)
  apro_err[i] <- absdif
  print(absdif)
  # plot(xs,ys,pch=".",col=ifelse(in.circle,"blue","red"),xlab='',ylab='',asp=1, main=paste("MC Approximation of Pi =",mc.pi))
}

plot(apro_err, runs, ylab='Approximation Error', xlab='Sample Size',col='red')

The problem you have in your code is that you are using i as the runs ( 1000 ...), and then you are using the same i to store inside apro_err[i] .您在代码中遇到的问题是您使用i作为运行( 1000 ...),然后您使用相同的i存储在apro_err[i]中。

I reformatted the code so that you now store the values correctly.我重新格式化了代码,以便您现在可以正确存储值。 This allows you to plot four points, one for each runsize, instead of just one.这使您可以 plot 四个点,每个运行大小一个,而不仅仅是一个。

runs <- c(1000, 10000, 100000, 1000000)
apro_err <- c()

PI_REAL <- 3.14159265
UNI_MIN <- -0.5
UNI_MAX <- 0.5

for (i in seq_along(runs)){
  #runif samples from a uniform distribution
  run <- runs[i]
  xs <- runif(run, min = UNI_MIN, max = UNI_MAX)
  ys <- runif(run, min = UNI_MIN, max = UNI_MAX)
  in.circle <- xs^2 + ys^2 <= UNI_MAX^2
  mc.pi <- (sum(in.circle)/run) * 4
  absdif <- abs(mc.pi - PI_REAL)
  apro_err[i] <- absdif
  print(absdif)
  # plot(xs,ys,pch=".",col=ifelse(in.circle,"blue","red"),xlab='',ylab='',asp=1, main=paste("MC Approximation of Pi =",mc.pi))
}

plot(apro_err, runs, ylab='Approximation Error', xlab='Sample Size',col='red')

Let me know if this was what you were seeking.让我知道这是否是您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM