Exercise

# Scalar random number generation

When you write R code, it usually makes sense to generate random numbers in a vectorized fashion. When you are in C++ however, you are allowed (even by your guilty conscience) to use loops and process the data element by element.

The R API gives you functions to generate a random number from one of the usual distributions, and Rcpp makes these functions accessible in the `R::`

namespace. For example, `R::rnorm(2, 3)`

gives you one random number from the Normal distribution with mean 2 and standard deviation 3. Notice that the `n`

argument from the "real" `rnorm()`

is not present. The Rcpp version always returns one number.

Go ahead and complete the function definition of `positive_rnorm()`

.

*Note: This last chapter is hard, so don't get discouraged if you can't complete the exercises in the first attempt. Remember the reward for completing this course: dramatically improving the performance of your R code!*

Instructions

**100 XP**

- Specify the return value,
`out`

as a numeric vector of size`n`

. *Read the looping code to see what each does.*- Generate a normal random number of mean
`mean`

and standard deviation`sd`

, assigning to`out[i]`

. - While
`out[i]`

is less than or equal to zero, try again.