Announcement

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

  • random number generator plus controlled sum constraint

    Dear all,
    In my project, Monte Carlo simulation is applied. But I have to control the sum of the observations as a constant while using a rnd command. For example, I want to generate an X~N(40, theta2) and set the observation number at 100. The sum then can be estimated as 4000. But using
    Code:
     gen x= 40+invnormal(uniform())
    can only ensure the sum close to 4000 but cannot make sure exactly equal to 4000. Does anyone knows how to reach this goal?
    2B or not 2B, that's a question!

  • #2
    My brute force approach from #9 in this link will give you an option of seeds.

    Code:
    *OVER 1000 TRIALS, EXTRACT SEED
    set obs 100
    forvalues i= 1/1000{
    gen seed`i'="`c(seed)'"
    gen x`i'= 40+invnormal(uniform())
    egen totalx`i'= total(x`i')
    }
    
    keep in 1
    *ssc install fastreshape
    keep seed* totalx*
    gen n=1
    fastreshape long seed totalx, i(n)
    
    *BROWSE OBSERVATIONS WHICH SUM TO 4000
    sort totalx
    browse if inrange(totalx,3999.99, 4000.10)
    
    *SELECT APPROPRIATE SEED, e.g., in OBS. No. 523 for me
    local seed = seed in 523
    
    *USE SEED
    clear
    set obs 100
    set seed `seed'
    gen x= 40+invnormal(uniform())
    egen totalx= total(x)
    list totalx in 1

    Code:
    . set seed `seed'
    
    .
    . gen x= 40+invnormal(uniform())
    
    .
    . egen totalx= total(x)
    
    .
    . list totalx in 1
    
         +----------+
         |   totalx |
         |----------|
      1. | 4000.048 |
         +----------+

    Comment


    • #3
      Take a look corr2data


      Code:
      . corr2data x, m(40) sd(1) n(100) double
      (obs 100)
      
      . sum
      
          Variable |        Obs        Mean    Std. Dev.       Min        Max
      -------------+---------------------------------------------------------
                 x |        100          40           1   37.64696   42.03049

      Comment

      Working...
      X