Results 1 to 34 of 34

Thread: [2008] How to achieve true 50/50 chance?

  1. #1

    Thread Starter
    Fanatic Member arsmakman's Avatar
    Join Date
    Dec 2001
    Location
    Leiden, Netherlands.
    Posts
    719

    Resolved [2008] How to achieve true 50/50 chance?

    I know I'm being quite pedantic here. But, what is the right way to get a true 50/50-chance with a generated random number? Say, to simulate the flip of a coin.

    This is what I mean:
    Code:
    Randomize()
    
    If Rnd() > .5 Then Debug.Print("Heads") Else Debug.Print("Tails")
    If Rnd() >= .5 Then Debug.Print("Heads") Else Debug.Print("Tails")
    Which of these two is the right one?

    I know this difference is close to nothing, but I'm doing some calculations on bell curves, in such a way that it requires true 50/50-chance.

    Thanks for any help,
    Alexander.
    Last edited by arsmakman; Feb 11th, 2009 at 02:03 PM. Reason: Resolved
    No matter how fool-proof your program is, there will always be a better fool.

    Was a post helpful to you? Rate it!

  2. #2
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    Re: [2008] How to achieve true 50/50 chance?

    why use the rnd function from VB6? there is a random class built into .NET

    here is one example, maybe you can modify it to your needs...
    Code:
            Dim myRandom As New Random()
            Dim totalHeads As Integer = 0
            Dim totalTails As Integer = 0
    
            For i As Integer = 1 To 100
                If myRandom.Next(1, 100) < 51 Then
                    totalHeads += 1
                Else
                    totalTails += 1
                End If
            Next
    
            MessageBox.Show(String.Format("Total Heads: {0}, Total Tails: {1}", totalHeads.ToString, totalTails.ToString))

  3. #3
    Frenzied Member
    Join Date
    Jun 2005
    Posts
    1,950

    Re: [2008] How to achieve true 50/50 chance?

    The statements will produce the same probability, you are only modifying the weighting.

    What you could do to make it even would be;

    Code:
                If i < 0.5 Then Debug.Print("Heads") 
                If i > 0.5 Then Debug.Print("Tails") 
                If i = 0.5 Then Debug.Print("Coin landed on its edge")
    An system with two states has one or more metastable states. You can never escape a 'third state' whatever you do.

    In your code, you are adding the probability of the third state to the probability of one of the other two states which will cause a small weighting difference. In reality the weighting is not predictable, because the metastable state depends on a huge number of factors. In the case of throwing a coin, air turbulence, temperature, the thickness of the coin, the surface it lands on, cosmic radiation etc. To be more succinct, these factors determine the "duration" of the metastable state, in one case that duration can be infinite.
    Last edited by Bulldog; Feb 11th, 2009 at 01:57 PM.

  4. #4

    Thread Starter
    Fanatic Member arsmakman's Avatar
    Join Date
    Dec 2001
    Location
    Leiden, Netherlands.
    Posts
    719

    Re: [2008] How to achieve true 50/50 chance?

    @Kleinma: Thanks, I didn't even know about the Random-type. I started programming back when VB6.0 was all the rage and slowly adapted my programming to .NET's ways on my own. This only forced me to change the things that are no longer supported. I guess I should pick up a VB2008 book sometime, but you how it is: ever so busy!

    @bulldog: That's a great take on it, but not really a proper solution.

    So, I guess this should work fine:
    Code:
    Dim myRandom As New Random()
    If myRandom.Next(0, 2) Then [It's heads] Else [It's tails]
    Right?
    Last edited by arsmakman; Feb 11th, 2009 at 02:01 PM.
    No matter how fool-proof your program is, there will always be a better fool.

    Was a post helpful to you? Rate it!

  5. #5
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: [2008] How to achieve true 50/50 chance?

    In .NET you have better ways to do this:

    vb.net Code:
    1. Dim myNumber As Integer, selected As String
    2. Dim r As New Random
    3. myNumber = r.Next(0, 2)
    4. selected = If(myNumber = 0, "Heads", "Tail")
    5. MessageBox.Show(selected)

    EDIT: Ohh... I'm so late
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  6. #6
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    Re: [2008] How to achieve true 50/50 chance?

    Quote Originally Posted by arsmakman
    @Kleinma: Thanks, I didn't even know about the Random-type. I started programming back when VB6.0 was all the rage and slowly adapted my programming to .NET's ways on my own. This only forced me to change the things that are no longer supported. I guess I should pick up a VB2008 book sometime, but you how it is: ever so busy!

    @bulldog: That's a great take on it, but not really a proper solution.

    So, I guess this should work fine:
    Code:
    Dim myRandom As New Random()
    If myRandom.Next(0, 2) Then [It's heads] Else [It's tails]
    Right?
    yes, that should work.. I actually forgot about the random.next() routine the high number param is not actually used (all numbers between the low number, and the high number -1 are used)... so in my example, you would actually want 101 as the high number... but yeah, that should do it for you.

  7. #7
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: [2008] How to achieve true 50/50 chance?

    Quote Originally Posted by arsmakman
    @Kleinma: Thanks, I didn't even know about the Random-type. I started programming back when VB6.0 was all the rage and slowly adapted my programming to .NET's ways on my own. This only forced me to change the things that are no longer supported. I guess I should pick up a VB2008 book sometime, but you how it is: ever so busy!

    @bulldog: That's a great take on it, but not really a proper solution.

    So, I guess this should work fine:
    Code:
    Dim myRandom As New Random()
    If myRandom.Next(0, 1) Then [It's heads] Else [It's tails]
    Right?
    The lower bound of Random.Next is inclusive, while the upper bound is exclusive.
    So to select between 0 & 1 only you will have to provide:
    myRandom.Next(0, 2)

    EDIT: AAAAhhhh.... late again as usual
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  8. #8
    Frenzied Member
    Join Date
    Jun 2005
    Posts
    1,950

    Re: [2008] How to achieve true 50/50 chance?

    But remember, there is no such thing as 50:50 chance.

    No matter how you draw it, your bell curve is symmetric either side of a metastable state. So to be truly accurate, you should represent that state or your weighting will always be slightly in error. It's Isaac Newton's fault this state is present

  9. #9

    Thread Starter
    Fanatic Member arsmakman's Avatar
    Join Date
    Dec 2001
    Location
    Leiden, Netherlands.
    Posts
    719

    Re: [2008] How to achieve true 50/50 chance?

    @Pradeep1210: No problem! Still helpful.

    @Kleinma: I noticed when my million coin flips all landed on tails.

    Also, I noticed that (Rnd() >= .5) is actually about 15% faster than Random.Next(0,2)...
    No matter how fool-proof your program is, there will always be a better fool.

    Was a post helpful to you? Rate it!

  10. #10
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    Re: [2008] How to achieve true 50/50 chance?

    that could be due to underlying differences in their implementations... one may be slightly "MORE" random than another, but I guess some testing would determine that.

    also remember that random numbers are something computers don't do very well, and they are really only pseudo random regardless of which implementation you use...

  11. #11
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: [2008] How to achieve true 50/50 chance?

    Quote Originally Posted by arsmakman

    Also, I noticed that (Rnd() >= .5) is actually about 15% faster than Random.Next(0,2)...
    Not really!

    Random is faster than Rnd()
    I did this test and it always comes out to be the winner.

    vb.net Code:
    1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    2.     Dim myNumber As Integer, selected As String
    3.  
    4.     'RND function
    5.     Dim rndTicks As Double = Now.Ticks
    6.     For i As Integer = 0 To 10000000
    7.         myNumber = Rnd() * 0.5
    8.         selected = If(myNumber > 5, "Heads", "Tail")
    9.     Next
    10.     rndTicks = Now.Ticks - rndTicks
    11.  
    12.     'RANDOM class
    13.     Dim randomTicks As Double = Now.Ticks
    14.     Dim r As New Random
    15.     For i As Integer = 0 To 10000000
    16.         myNumber = r.Next(0, 2)
    17.         selected = If(myNumber = 0, "Heads", "Tail")
    18.     Next
    19.     randomTicks = Now.Ticks - randomTicks
    20.     MessageBox.Show("Rnd   : " & rndTicks & vbCrLf & "Random: " & randomTicks)
    21.  
    22. End Sub

    Pradeep
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  12. #12
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: [2008] How to achieve true 50/50 chance?

    "But remember, there is no such thing as 50:50 chance." what is the third state in alive / dead?
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  13. #13
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    Re: [2008] How to achieve true 50/50 chance?

    Quote Originally Posted by Pradeep1210
    Not really!

    Random is faster than Rnd()
    I did this test and it always comes out to be the winner.

    vb.net Code:
    1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    2.     Dim myNumber As Integer, selected As String
    3.  
    4.     'RND function
    5.     Dim rndTicks As Double = Now.Ticks
    6.     For i As Integer = 0 To 10000000
    7.         myNumber = Rnd() * 0.5
    8.         selected = If(myNumber > 5, "Heads", "Tail")
    9.     Next
    10.     rndTicks = Now.Ticks - rndTicks
    11.  
    12.     'RANDOM class
    13.     Dim randomTicks As Double = Now.Ticks
    14.     Dim r As New Random
    15.     For i As Integer = 0 To 10000000
    16.         myNumber = r.Next(0, 2)
    17.         selected = If(myNumber = 0, "Heads", "Tail")
    18.     Next
    19.     randomTicks = Now.Ticks - randomTicks
    20.     MessageBox.Show("Rnd   : " & rndTicks & vbCrLf & "Random: " & randomTicks)
    21.  
    22. End Sub

    Pradeep
    tisk, tisk.. you must be coding with option strict OFF...

    try turning it on, which will give you a compile error on that code, which to fix, you would need to change myNumber from integer to double. Then run it.

    The difference you probably saw, is the runtime doing a conversion from double to integer, causing more time to be taken up in the first loop your code runs...

  14. #14
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    Re: [2008] How to achieve true 50/50 chance?

    Quote Originally Posted by dbasnett
    "But remember, there is no such thing as 50:50 chance." what is the third state in alive / dead?
    ummm.. haven't you ever seen the princess bride??? you can be "mostly dead"

  15. #15
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: [2008] How to achieve true 50/50 chance?

    almost three times faster

    Code:
        Sub Main()
            Const testLen As Integer = 100000
            Dim r As New Random, stpw As New Stopwatch
            Dim dnr As Single, nn As Double
            Randomize()
            For z As Integer = 1 To 5
                stpw.Stop() : stpw.Reset() : stpw.Start()
                For x As Integer = 1 To testLen
                    dnr = Rnd()
                Next
                stpw.Stop() : Console.WriteLine("RND - " & stpw.ElapsedTicks.ToString)
    
    
                stpw.Stop() : stpw.Reset() : stpw.Start()
                For x As Integer = 1 To testLen
                    nn = r.NextDouble
                Next
                stpw.Stop() : Console.WriteLine("Random - " & stpw.ElapsedTicks.ToString)
            Next
            Console.ReadLine()
        End Sub
        'RND - 28643
        'Random - 10214
        'RND - 28971
        'Random - 9845
        'RND - 50637
        'Random - 11283
        'RND - 28680
        'Random - 10007
        'RND - 28776
        'Random - 9988
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  16. #16
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    Re: [2008] How to achieve true 50/50 chance?

    yes, but once you go from just calling

    r.NextDouble

    to

    r.Next(0,2)

    there is a big performance hit

  17. #17
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: [2008] How to achieve true 50/50 chance?

    Quote Originally Posted by kleinma
    ummm.. haven't you ever seen the princess bride??? you can be "mostly dead"
    what a funny movie!
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  18. #18
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: [2008] How to achieve true 50/50 chance?

    ok

    Code:
            Const testLen As Integer = 100000
            Dim r As New Random, stpw As New Stopwatch
            Dim dnr As Single, nn As Double
            Dim i As Integer
            Randomize()
            For z As Integer = 1 To 5
                stpw.Stop() : stpw.Reset() : stpw.Start()
                For x As Integer = 1 To testLen
                    i = CInt((10 - 1 + 1) * Rnd())
                Next
                stpw.Stop() : Console.WriteLine("RND - " & stpw.ElapsedTicks.ToString)
    
    
                stpw.Stop() : stpw.Reset() : stpw.Start()
                For x As Integer = 1 To testLen
                    i = r.Next(1, 11)
                Next
                stpw.Stop() : Console.WriteLine("Random - " & stpw.ElapsedTicks.ToString)
            Next
            Console.ReadLine()
        End Sub
        'RND - 69809
        'Random - 22037
        'RND - 52530
        'Random - 24019
        'RND - 56144
        'Random - 20641
        'RND - 57395
        'Random - 20600
        'RND - 55972
        'Random - 20074
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  19. #19
    Frenzied Member
    Join Date
    Jun 2005
    Posts
    1,950

    Re: [2008] How to achieve true 50/50 chance?

    Quote Originally Posted by dbasnett
    "But remember, there is no such thing as 50:50 chance." what is the third state in alive / dead?
    A human being is not a system with defined stable states.

    By a system, I refer to any construction, mechanical, electrical that has the task of arbitration.

    So to simulate a 50:50 chance in software, there are two approaches
    - take into account the third metastable state
    - accept the occurrence, but discard the result and repeat the arbitration

    So in code, to get a 50:50 state you can do;

    Accept it;
    Code:
            Dim i As Double = Rnd()
            If i < 0.5 Then MessageBox.Show("Heads")
            If i > 0.5 Then MessageBox.Show("Tails")
            If i = 0.5 Then MessageBox.Show("Coin on side")
    Ignore it;
    Code:
           ' The disadvantage of this method is that it can potentially run forever if the 
           ' Rnd function was truly random
            i = Rnd()
            While i = 0.5
                i = Rnd()
            End While
            If i < 0.5 Then MessageBox.Show("Heads")
            If i > 0.5 Then MessageBox.Show("Tails")
    Within the electronic systems I design, we have to take metastability into account to prevent computers from hanging, auto-pilot from oscillating, machines incurring destructive vibration etc. etc. This is achieved by examining systems in the s-domain and plotting pole/zero diagrams. There are strategies to deal with it, but it can never be overcome. I actually have 5 patents for circuits that reduce the probability of occurrence or snap out of it once it occurs.

    Things are much more complicated in reality because even a simple binary system has at least one metastable state, in many there are multiple metastable states. Going one level further there is a very serious problem called the isochronic fork, which can cause disastrous results in systems. If you'd like to find out more about this, pick up a book on Systems Engineering, it's a very, very interesting subject. There is in fact a system model for a human being, which is used to determine stability of systems such as fly by wire, where signals from control surfaces are slightly delayed. Pilot induced oscillation (PIO) was a common occurrence in the first fly by wire aircraft, where the loop dynamics were not optimum, the crew ended up porpoising the aircraft.

    There is a human example I can give, if a human is indecisive about carrying on down the freeway or taking the exit, many vehicles have crashed into the central barrier because the drivers arbitration was metastable. I have not crashed a car that way but I have experienced it and even started wobbling the wheel left/right until I finally snapped out of it and went one way. In my case the duration of the metastable event was shorter than the remaining time before crashing.
    Last edited by Bulldog; Feb 11th, 2009 at 03:10 PM.

  20. #20
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    Re: [2008] How to achieve true 50/50 chance?

    lol, i like the (10 - 1 + 1)

    my only point was he is right that calling rnd to get a Single datatype, is quicker than calling random.next to get an integer type...

    if its a matter of trying to get a random 50/50 value on something, then you shouldn't need to be concerned with the datatypes returned... with all the casting and what not, it does not make for a very clean test.

  21. #21
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: [2008] How to achieve true 50/50 chance?

    I thought doubles were slow and integers were fast. But here's just the opposite

    Here's something interesting. I stripped off the assignments to get pure result of random number generation only.
    vb.net Code:
    1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    2.     'RANDOM (double)
    3.     Dim randomDTicks As Double = Now.Ticks
    4.     Dim rd As New Random
    5.     For i As Integer = 0 To 10000000
    6.         rd.NextDouble()
    7.     Next
    8.     randomDTicks = Now.Ticks - randomDTicks
    9.  
    10.     'RANDOM (integer)
    11.     Dim randomITicks As Double = Now.Ticks
    12.     Dim ri As New Random
    13.     For i As Integer = 0 To 10000000
    14.         ri.Next(0, 10)
    15.     Next
    16.     randomITicks = Now.Ticks - randomITicks
    17.  
    18.     'RND function
    19.     Dim rndTicks As Double = Now.Ticks
    20.     For i As Integer = 0 To 10000000
    21.         Rnd()
    22.     Next
    23.     rndTicks = Now.Ticks - rndTicks
    24.  
    25.     'MessageBox.Show("Rnd   : " & rndTicks & vbCrLf & "Random: " & randomTicks)
    26.     Debug.Print("Random(D): " & randomDTicks)
    27.     Debug.Print("Random(I): " & randomITicks)
    28.     Debug.Print("Rnd      : " & rndTicks)
    29. End Sub

    Output:
    Code:
    Random(D): 2031232
    Random(I): 4062464
    Rnd      : 5781248
    Random(D): 1875072
    Random(I): 4218752
    Rnd      : 5624960
    Random(D): 2031360
    Random(I): 4218752
    Rnd      : 5624960
    Random(D): 1875072
    Random(I): 4218752
    Rnd      : 5624960
    So:
    1. Random.NextDouble and Random.Next both are faster than Rnd().
    2. Random.NextDouble is faster than Random.Next.

    Pradeep
    Last edited by Pradeep1210; Feb 11th, 2009 at 03:17 PM.
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  22. #22
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: [2008] How to achieve true 50/50 chance?

    isn't it fair to compare apples to apples when making that kind of statement?

    Code:
            Const testLen As Integer = 100000
            Dim r As New Random, stpw As New Stopwatch
            Dim dnr As Single, nn As Double
            Dim i As Integer, tORf As Boolean
            Randomize()
            For z As Integer = 1 To 5
                stpw.Stop() : stpw.Reset() : stpw.Start()
                For x As Integer = 1 To testLen
                    dnr = Rnd()
                    tORf = If(dnr < 0.5, True, False)
                Next
                stpw.Stop() : Console.WriteLine("RND - " & stpw.ElapsedTicks.ToString)
    
    
                stpw.Stop() : stpw.Reset() : stpw.Start()
                For x As Integer = 1 To testLen
                    nn = r.NextDouble
                    tORf = If(nn < 0.5, True, False)
                Next
                stpw.Stop() : Console.WriteLine("Random - " & stpw.ElapsedTicks.ToString)
            Next
            Console.ReadLine()
    results
    RND - 32211
    Random - 13328
    RND - 31299
    Random - 14199
    RND - 33941
    Random - 12482
    RND - 32154
    Random - 12495
    RND - 31590
    Random - 17168

    the only way rnd is faster is if you make random do a conversion that rnd doesn't do.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  23. #23
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: [2008] How to achieve true 50/50 chance?

    the native mode of random is based on Knuth, "In this section we shall consider methods of generating a sequence of random fractions..." so i would expect for real numbers to be the fastest.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  24. #24
    Frenzied Member
    Join Date
    Mar 2005
    Location
    Sector 001
    Posts
    1,577

    Re: [2008] How to achieve true 50/50 chance?

    Quote Originally Posted by Bulldog
    Within the electronic systems I design, we have to take metastability into account to prevent computers from hanging, auto-pilot from oscillating, machines incurring destructive vibration etc. etc. This is achieved by examining systems in the s-domain and plotting pole/zero diagrams. There are strategies to deal with it, but it can never be overcome. I actually have 5 patents for circuits that reduce the probability of occurrence or snap out of it once it occurs.

    Things are much more complicated in reality because even a simple binary system has at least one metastable state, in many there are multiple metastable states. Going one level further there is a very serious problem called the isochronic fork, which can cause disastrous results in systems. If you'd like to find out more about this, pick up a book on Systems Engineering, it's a very, very interesting subject. There is in fact a system model for a human being, which is used to determine stability of systems such as fly by wire, where signals from control surfaces are slightly delayed. Pilot induced oscillation (PIO) was a common occurrence in the first fly by wire aircraft, where the loop dynamics were not optimum, the crew ended up porpoising the aircraft.

    There is a human example I can give, if a human is indecisive about carrying on down the freeway or taking the exit, many vehicles have crashed into the central barrier because the drivers arbitration was metastable. I have not crashed a car that way but I have experienced it and even started wobbling the wheel left/right until I finally snapped out of it and went one way. In my case the duration of the metastable event was shorter than the remaining time before crashing.
    Nice introduction.
    VB 2005, Win Xp Pro sp2

  25. #25
    Stack Overflow mod​erator
    Join Date
    May 2008
    Location
    British Columbia, Canada
    Posts
    2,824

    Re: [2008] How to achieve true 50/50 chance?

    Honestly, I do not have the time to read all of these posts. I will just give you a solution:

    There is really no such thing as a random number. That I noticed when I tried to program a "random angle" Arkanoid game. The "random" angle was always the same, because the timing was the same. The only solution I can see is using a timer or another thread that will (randomly) re-randomize the randomizer.

    Try this:
    vb Code:
    1. Dim t As Thread
    2. Private Sub Form_Load(sender,e) Handles MyBase.Load
    3.           Randomize()
    4.           t = New Thread(AddressOf ReRandomize)
    5.           t.Start
    6. End Sub
    7. Private Function CoinFlip() As Integer '0:Tails,1:Heads,2:Coin on side
    8.           'The probability of the coin landing on its side depends on the number you use.
    9.           Dim rInt As Integer = CInt(Int(Rnd()*100))
    10.           If rInt < 50 Then
    11.                     Return 0
    12.           ElseIf rint > 50 Then
    13.                     Return 1
    14.           Else
    15.                     Return 2
    16.           End If
    17. End Function
    18. Private Sub ReRandomize()
    19.           While True 'use some class-level boolean to stop this
    20.                     If CInt(Int(Rnd()*7)) < 3 Then
    21.                               Randomize()
    22.                     End If
    23.                     Threading.Thread.Sleep(CInt(Int(Rnd()*122))
    24.           End While
    25. End Sub

    This is about the best random number generator that I can give you.
    End Sub
    Last edited by minitech; Feb 13th, 2009 at 07:03 PM.

  26. #26
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: [2008] How to achieve true 50/50 chance?

    @mini - please use code tags and please post code that will compile with
    Option Strict On
    Code:
            Dim rInt As Integer = Int(Rnd() * 100)'Error Option Strict On disallows implicit conversions from 'Single' to 'Integer'
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  27. #27
    Frenzied Member
    Join Date
    Jun 2005
    Posts
    1,950

    Re: [2008] How to achieve true 50/50 chance?

    Code:
    There is really no such thing as a random number.
    The number is not random because the Rnd function is actually a calculation which always starts using the same "seed". The randomize function only advances the calculation by a pseudo-random number of cycles or restarts the sequence with a different seed value. So even with randomize you can end up with the exact same sequence.

    To get a random number in VB, you can take the number of milliseconds off of the current date/time. That gives you a number between 0 and 9, or 0 and 99 or 0 and 999 depending on the number of digits that you take. In a multi-threaded O/S, that 'number' really is random since it depends on your computers activity and the sequence will always be truly different.

  28. #28
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: [2008] How to achieve true 50/50 chance?

    .Nets Random uses ticks in the default constructor
    Dim r As New Random 'use ticks

    where the following will generate the same sequence
    Dim r As New Random(100) 'generate the same pseudo random sequence


    if you are using 2008 you shouldn't be using Randomize / Rnd.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  29. #29
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    Re: [2008] How to achieve true 50/50 chance?

    Quote Originally Posted by Bulldog
    The number is not random because the Rnd function is actually a calculation which always starts using the same "seed".
    this is only true if randomize() is not called...


    from MSDN:

    For any given initial seed, the same number sequence is generated because each successive call to the Rnd function uses the previously generated number as a seed for the next number in the sequence.

    Before calling Rnd, use the Randomize statement without an argument to initialize the random-number generator with a seed based on the system timer.

  30. #30
    Frenzied Member
    Join Date
    Jun 2005
    Posts
    1,950

    Re: [2008] How to achieve true 50/50 chance?

    But its still not random unless you use randomize every time you request a random number i.e. as part of the loop and not just once.

    If you randomize, you start the sequence with a new seed. For a given seed, you always get the same subsequent sequence. So all you are doing by randomizing is selecting a different sequence from a fixed set of sequences.

    If you randomize on each loop, then you jump about between these sequences, so I would agree that this would give a much better approximation of a random list.

    (Mind you if the only activity on your computer was your program, this would not be random either because the randomize would always generate the same seed sequence. This is because the system timer would increment by the same amount between operations. The sequence space is however very much larger).

  31. #31
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,687

    Re: [2008] How to achieve true 50/50 chance?

    Bulldog - true, BUT.... you also have to watch the speed of the loop... if it is too fast, you can go multiple iterations calling Randomize() which ends up generating the same seed, and so Rnd() produces the same number (because it will keep returning the same first number in the sequence.) - never mind, I see that you already noted that.

    But yes, once you know how Rnd works, you can use it to an advantage, if used properly.
    Using the Random class seems to have eliminated some of that problem.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  32. #32
    Stack Overflow mod​erator
    Join Date
    May 2008
    Location
    British Columbia, Canada
    Posts
    2,824

    Smile Re: [2008] How to achieve true 50/50 chance?

    Quote Originally Posted by dbasnett
    @mini - please use code tags and please post code that will compile with
    Option Strict On
    Code:
            Dim rInt As Integer = Int(Rnd() * 100)'Error Option Strict On disallows implicit conversions from 'Single' to 'Integer'
    I use option strict and it compiles just fine.
    But I'll change anyways. As for the tags, sorry. Anyways, I have finished the code.

  33. #33
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: [2008] How to achieve true 50/50 chance?

    Quote Originally Posted by minitech
    As for the tags, sorry. Anyways, I have finished the code.
    The difference is more or less the same unless you have indented it properly
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  34. #34
    Stack Overflow mod​erator
    Join Date
    May 2008
    Location
    British Columbia, Canada
    Posts
    2,824

    Re: [2008] How to achieve true 50/50 chance?

    Well, I've indented it now. But no matter, it's code that will work. (I hope)

Posting Permissions

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



Click Here to Expand Forum to Full Width