Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Random numbers within interval

    Hey Statlisters,

    I am using Stata 14 and trying to draw random numbers and post them observation by observation with the command -postfile- into a new data file. Now when a number is drawn I would like my loop to discard this number if it lies outside of a given interval and draw as long until it finally lies in it. I looked at different examples in the Stata Blog with random numbers being drawn from a uniform distribution out of a given interval but I would like to use -rnormal(m, s)- and could not figure it out.

    This is how far I have come with my code:
    Code:
    set seed 1234
    
    *Set the values of parameters
    
    scalar mean_d = 1
    scalar sigma = 1.5
    scalar ub = 3          *upper bound of interval
    scalar lb = 1           *lower bound of interval
    gen obs=.
    gen obsid =.
     
    postfile `sim' obsid obs control`n' using results, replace
            quietly {
            forvalues i = 1/10000 {
            replace obs = rnormal(`mean_d', `sigma')
            scalar control = obs<`ub' & obs>`lb'
            replace obsid = `i'
            post `sim' (obsid) (obs) (control)
            }
    }
    postclose `sim'
    Anybody with some advice on how to implement that?

    Cheers

    Philipp

  • #2
    It shouldn't be too hard to implement a truncated normal distribution. A couple of questions:

    1. Why are you using postfile to do this? From your code, you're already putting the values into the resident dataset. You might as well take advantage of the vectorizing nature of the rnormal() Stata function and generate the "obs" variable in a 10 000-observation in-memory dataset. It would be much faster than looping and posting.

    2. If you're going to truncate at the mean, then why not use a "folded normal" distribution and add the mean afterward?
    Code:
    generate double obs = abs(rnormal(0, 1.5)) + lb
    generate byte control = obs > ub
    Be sure to keep straight the difference between a temporary scalar (`mean_d', `sigma', `lb', `ub') and permanent ones (mean_d, sigma, lb, ub).

    Comment


    • #3
      Dear Joseph,

      Sorry for my late reply. Thank you very much for your reply and suggestions. I am rather new to Stata and found postfile in my search for simulation commands. Thats why I chose it.

      I am trying to implement your suggestions now for a truncated and folded normal. I also found the command rtnorm, that creats random variates from a truncated normal distribution.

      Comment

      Working...
      X