Announcement

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

  • random numbers/variables by loop

    Dear All, Why are the following two codes generate different values/variables?
    Code:
    clear
    set seed 8818
    set obs 1000
    forval i=1/1000{
    gen x_`i'=rchi2(5)
    }
    
    
    clear
    set obs 1000
    forval i=1/1000{
    set seed 8818
    gen x_`i'=rchi2(5)
    }
    Thanks.
    Ho-Chuan (River) Huang
    Stata 19.0, MP(4)

  • #2
    The second code incorrectly sets the seed, essentially resetting it (and the state of the pseudorandom number generator) with each iteration. Effectively, you would have 1000 copies of the same variable.

    Comment


    • #3
      Dear Leonardo, Thanks for the answer. I noticed that. My question is that, why does the first code generate values for different variables when I set seed in the first place?
      Ho-Chuan (River) Huang
      Stata 19.0, MP(4)

      Comment


      • #4
        Setting the seed effectively picks a starting point for random numbers to be generated. You set it once at the top of your script, then proceed with whatever you need to do. Any random numbers generated from this point on change the state of the generator, somewhat analogous to a ratchet, clicking off new numbers one by one. This is why the first code creates random variables and the second code doesn't. (There is always an implicit and new seed set everytime Stata starts. I think it is related to the current system time, but I don't recall right now.)

        Another way to look at it is to think about each iteration of the loop in relation to the changing seed. In the second code, the sequence of random numbers is only allowed to grow as large as the number of observations, 1000 here. Then the new iteration starts, the seed is reset and the sequence repeats. In the first code, no such reset occurs and the steam of random numbers is 1000^2 in length.

        Comment


        • #5
          Dear Leonardo, Thanks a lot for the explanation.
          Ho-Chuan (River) Huang
          Stata 19.0, MP(4)

          Comment

          Working...
          X