I need to generate random numbers until the condition(sum of the difference of each random number is 3000.) is satisfied.
and random numbers are already generated from the truncated normal distribution.
I already try to use while loop while(1) and if , but it didn't work properly.
How can I generate new random number sequence with the condition?
truncnorm_rn <- rtruncnorm(1000,0,30,0,1)
a <- 0
b <- 0
c <- 0 # sum of diffrences between truncnorm random number
d <- NULL # New sequnce with condition
while(1){
a <- truncnorm_rn[1]
b <- truncnorm_rn[2]
c <- sum(a - b)
if(c > 3000) break
}
CodePudding user response:
What you're asking for is the following. Which will generate a new truncated normal series of size 1,000 until there is an absolute difference greater than 3,000 for all numbers in the series.
library(truncnorm)
abs_diff <- 0
i <- 0
while(abs_diff <= 3000) {
i <- i 1
series <- rtruncnorm(n = 1000, a = 0, b = 30, mean = 0, sd = 1)
abs_diff <- sum(abs(diff(series)))
}
# the iteration where the sum of absolute differences is > 3,000
i
# the series of numbers that satisfied the condition
series
However, I don't know if your condition will be satisfied with those parameters for the truncated normal (quickly, at least). I ran this for 125k iterations and the condition was not satisfied. If you change the mean
or sd
(see example code below) you'll find a series that satisfies the condition in a more reasonable amount of time.
abs_diff <- 0
i <- 0
while(abs_diff <= 3000) {
i <- i 1
series <- rtruncnorm(n = 1000, a = 0, b = 30, mean = 5, sd = 2.6)
abs_diff <- sum(abs(diff(series)))
}