PDA

View Full Version : Probability & RNDF



marcuslee
17-11-2010, 09:51
Concerning ˇmpáct!, I've been thinking about how to have events happen based upon a certain probability. For example, there is a 1% chance that something will happen. Or, there is a 30% chance that something else will happen. How can I capture this in code?

I've thought of the following:



x = RND(1, 100)
IF x <= PercentVariable then <<do something>>


So, if there is a 1% chance that something will happen, x will have to be 1. If there is a 30% chance, x will have to be 30 or less. Does this capture the probability I am looking for?




Mark

danbaron
18-11-2010, 07:46
I ran the following thinBasic program, and the output was, 29,994,029.

That seems pretty good, since, perfection would be, 30,000,000.

(Apparently, the generated distribution is very close to uniform, so that the statement, "If Rnd <= 0.3", should be true, almost exactly 30% of the time.)

:p
Dan


Uses "console"

Global i, c As Long

Function TBMain()

' Seed the random number generator using the number of elapsed seconds since midnight.
Randomize
' (To instead make a reproducible sequence, use a constant seed, like, "Randomize(2)".)
' (Note that, "Randomize()", produces the same sequence as, "Randomize(0)".)

c = 0

' Generate 100,000,000 extended precision random values, and determine how many are less than or equal to 0.3.

For i = 1 To 100000000
If Rnd <= 0.3 Then c += 1
Next

Console_WriteLine(c)

WaitKey
End Function