Generate random numbers using For Loop
R
# initialize a variable to store the random number x <- 0 # use a for loop to generate random numbers from a uniform distribution for (i in 1:100) { # generate a random number between 0 and 1 x <- runif (1) # print the random number print (x) # check if the random number is greater than 0.9 if (x > 0.9) { # break the loop break } } |
Output
[1] 0.5482922 [1] 0.81156 [1] 0.3938314 [1] 0.9569094
- 1. First, it initializes a variable called x and assigns it the value of 0. This variable will store the random number that will be generated in each iteration of the loop.
- 2. Next, it uses a for loop to repeat a block of code 100 times. The for loop has a variable called i that takes values from 1 to 100 in each iteration. The for loop is enclosed by curly braces {} that indicate the start and end of the loop body.
- 3. Inside the loop body, the code does the following:
- It generates a random number between 0 and 1 using the runif function, which takes one argument: the number of random numbers to generate. In this case, it is 1. The random number is assigned to the variable x.
- It prints the value of x using the print function, which displays the output on the console.
- It checks if the value of x is greater than 0.9 using the if statement, which evaluates a logical condition and executes a block of code if it is true. The if statement is also enclosed by curly braces {} that indicate the start and end of the conditional block.
- Inside the conditional block, the code uses the break statement, which terminates the execution of the loop and jumps out of it.
- After the loop ends, the code stops running.
Generating Random Numbers Until Some Condition Is Met in R
R Language is mainly used for machine learning, statistics, and data analysis. Objects, functions, and R packages can easily be created by R. However we can use this language for other purposes like generating random numbers until a number greater than 0.9 is generated. We can do that using loops as R supports three kinds of loops.