简体   繁体   中英

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:

在此处输入图像描述

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:

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 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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