Consulting

Results 1 to 4 of 4

Thread: Use of Randomize statement

  1. #1
    Mac Moderator VBAX Guru mikerickson's Avatar
    Joined
    May 2007
    Location
    Davis CA
    Posts
    2,778

    Use of Randomize statement

    Considering the following code, am I correct that

    1) Line A is not needed, but both B and C are.

    2) This is equivilant to randomTotal = Int(50000 * Rnd())

    Dim didget(0 To 4) As Integer, i As Integer, randomTotal As Long
    
    Randomize: Rem line A
    For i = 0 To 3
        Randomize: Rem line B
        didget(i) = Int(10 * Rnd())
    Next i
    Randomize: Rem line C
    didget(4) = Int(5 * Rnd())
    
    For i = 0 To 4
        randomTotal = randomTotal + didget(i) * (10 ^ i)
    Next i
    Thanks in advance.

  2. #2
    Administrator
    Chat VP
    VBAX Guru johnske's Avatar
    Joined
    Jul 2004
    Location
    Townsville, Australia
    Posts
    2,872
    Location
    yes line A is not really needed but B and C are. to obtain more truly random numbers, randomize is needed to initialize Rnd functions random number generator and get a new seed. if not used, the Rnd function uses the same number as a seed the first time it is called and thereafter uses the last generated number as a seed value.
    You know you're really in trouble when the light at the end of the tunnel turns out to be the headlight of a train hurtling towards you

    The major part of getting the right answer lies in asking the right question...


    Made your code more readable, use VBA tags (this automatically inserts [vba] at the start of your code, and [/vba ] at the end of your code) | Help those helping you by marking your thread solved when it is.

  3. #3
    VBAX Regular
    Joined
    Sep 2007
    Location
    Singapore
    Posts
    63
    Quote Originally Posted by mikerickson
    Considering the following code, am I correct that
    2) This is equivilant to randomTotal = Int(50000 * Rnd())
    I've tried it out step-by-step and there's a small difference. The loop method will return a number that is larger than the single line method. My workings are in the attached workook; I hope I have interpreted the question correctly.

  4. #4
    Mac Moderator VBAX Guru mikerickson's Avatar
    Joined
    May 2007
    Location
    Davis CA
    Posts
    2,778
    Thanks all. I need to randomly select a number < 100! and this looks like the right technique.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •