Results 1 to 19 of 19

Thread: random number formula

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Jun 2002
    Posts
    110

    random number formula

    i heard from my algebra teacher that there is a way to write a formula that generates random numbers.. its illogical to me but if anyone knows it then please let me know.. im trying to rewrite the rnd() function in vb

  2. #2
    Fanatic Member bugzpodder's Avatar
    Join Date
    Jun 2002
    Location
    Ontario, Canada
    Posts
    787
    depends on how random you get. if you are just getting values occasionally you can just get the time and extract the unit digit - but thats just integers between one to ten. however if you want to use this method to get a bunch of random numbers at the same time, you will end up with the same digit every time
    Massey RuleZ! ^-^__Cheers!__^-^ Massey RuleZ!


    Did you know that...
    The probability that a random rational number has an even denominator is 1/3 (Salamin and Gosper 1972)? This result is independently verified by me (2002)!

  3. #3

    Thread Starter
    Lively Member
    Join Date
    Jun 2002
    Posts
    110
    what would "this method" be... whats the formula

  4. #4
    Fanatic Member riis's Avatar
    Join Date
    Nov 2001
    Posts
    551
    For functions which calculate random values a seed value is necessary. If you always use the same seed value, then you'll always get the same 'random' numbers. Because of that, the actual time (seconds after midnight, or seconds after Jan 1, 1970) is used often.

  5. #5
    Frenzied Member
    Join Date
    Jul 2002
    Posts
    1,370
    There are lots of random number generator algorithms - VB uses one that in a class called a pseudo-random number generator (PRNG)

    From MSDN:
    SUMMARY
    The RND function in Visual Basic generates pseudo-random numbers according to a specific algorithm. For certain scientific or statistical studies it might be important to understand how these numbers are generated. This article documents the algorithm used.

    A full treatise on the statistical nature of this algorithm is beyond the scope of this article but the topic is widely discussed in the scientific literature.
    MORE INFORMATION
    Microsoft Visual Basic uses the linear-congruential method for pseudo-random number generation in the RND function. The following pseudo code documents the algorithm used:
    x1 = ( x0 * a + c ) MOD (2^24)

    where:

    x1 = new value
    x0 = previous value (an initial value of 327680 is used by Visual Basic)
    a = 1140671485
    c = 12820163

    The 'MOD' operator in the formula above returns the integer remainder after an integer division.

    The expression x1/(2^24) will then return the floating-point number between 0.0 and 1.0 that is returned by the RND function.

    Note that the above algorithm cannot be implemented in Visual Basic code in such a way that the random number sequence generated by the RND function can be reproduced. This is because internally Visual Basic uses an unsigned long data type that is not supported by the Visual Basic language.

    The following C/C++ code can be used to generate the first ten pseudo-random numbers that Visual Basic generates:
    #include "stdafx.h"

    int main(int argc, char* argv[])
    {
    unsigned long rndVal;

    rndVal = 0x50000L;
    int i;
    float rndFloat;

    for (i=0;i<10;i++)
    {
    rndVal = (rndVal * 0x43fd43fdL + 0xc39ec3L) & 0xffffffL;
    rndFloat = (float)rndVal / (float)16777216.0;
    printf("Value is %.15f\n",rndFloat);
    }
    return 0;
    }

    Note that, by default, the Rnd() function will return the same sequence of pseudo-random numbers each time the program is run. For some purposes (such as statistical studies where repeatability is required) this may be appropriate. For other types of applications, such as games, this may not be appropriate. If a different sequence is required, use the Randomize statement prior to the first call to Rnd(). This will initialize the random number seed by using the system timer. If a different sequence is required but must be repeatable in future, use the syntax Randomize X where X is some specific numeric value.

    It is important to recognize that Rnd() returns a new sequence for each component in which it is used; that is, if your main EXE generates one sequence and uses a Visual Basic ActiveX DLL to generate a sequence also, these sequences are independent of one another.
    REFERENCES
    For additional information about how earlier versions of Microsoft Basic generate pseudo-random numbers, please click the article number below to view the article in the Microsoft Knowledge Base:

    28150 RND and RANDOMIZE Alternatives for Generating Random Numbers


  6. #6
    Frenzied Member
    Join Date
    Jul 1999
    Location
    Huntingdon Valley, PA 19006
    Posts
    1,151
    Try your local library or an internet search. One size does not fit all here. My MathCad7 software provides almost 20 pseudo random number generators.

    Note that random numbers is a misleading phrase. There are random processes (EG: Radioactive decay). There are sequences of numbers which pass certain statistical tests, and/or which can be used to simulate random processes. It is not exactly correct to talk about random numbers idependently of some random process.
    Live long & prosper.

    The Dinosaur from prehistoric era prior to computers.

    Eschew obfuscation!
    If a billion people believe a foolish idea, it is still a foolish idea!
    VB.net 2010 Express
    64Bit & 32Bit Windows 7 & Windows XP. I run 4 operating systems on a single PC.

  7. #7
    Addicted Member
    Join Date
    Aug 2002
    Location
    London UK
    Posts
    255
    Anyone can generate pseudo-random numbers using something like Microsoft used in Visual Basic. Generating perfectly random numbers is impossible, on a computer or otherwise.

    Think of it in terms of a continuous random variable.

    P(X = x) = 0, i.e. the probability of a randomly chosen integer is a certain integer 'x', is zero.

    E(X) = 0, because the expected value of X is the mean value of all the values X can take, and since positive integers cancel out negative ones, the number left is zero.

    How can you generate a random variable when you're expecting it's value to be zero?
    Not at all related to sheep...

  8. #8
    So Unbanned DiGiTaIErRoR's Avatar
    Join Date
    Apr 1999
    Location
    /dev/null
    Posts
    4,111
    Originally posted by A$$Bandit
    Anyone can generate pseudo-random numbers using something like Microsoft used in Visual Basic. Generating perfectly random numbers is impossible, on a computer or otherwise.

    Think of it in terms of a continuous random variable.

    P(X = x) = 0, i.e. the probability of a randomly chosen integer is a certain integer 'x', is zero.

    E(X) = 0, because the expected value of X is the mean value of all the values X can take, and since positive integers cancel out negative ones, the number left is zero.

    How can you generate a random variable when you're expecting it's value to be zero?
    It's just that 0 would be the technical mean of ANY(-infinity to +infinity) random number.

  9. #9
    transcendental analytic kedaman's Avatar
    Join Date
    Mar 2000
    Location
    0x002F2EA8
    Posts
    7,221
    Originally posted by DiGiTaIErRoR
    It's just that 0 would be the technical mean of ANY(-infinity to +infinity) random number.
    is there any proof for this?
    Use
    writing software in C++ is like driving rivets into steel beam with a toothpick.
    writing haskell makes your life easier:
    reverse (p (6*9)) where p x|x==0=""|True=chr (48+z): p y where (y,z)=divMod x 13
    To throw away OOP for low level languages is myopia, to keep OOP is hyperopia. To throw away OOP for a high level language is insight.

  10. #10
    Fanatic Member alkatran's Avatar
    Join Date
    Apr 2002
    Location
    Canada
    Posts
    860
    If you had had true randomization, and "threw 2 dice" alot, would the sum of both dice still be 7 the majority of the time?
    Don't pay attention to this signature, it's contradictory.

  11. #11
    Frenzied Member
    Join Date
    Jul 1999
    Location
    Huntingdon Valley, PA 19006
    Posts
    1,151
    Alkatran: If you mean plurality instead of majority, you are correct. A total of seven is expected to occur 1/6 of the time, which is more often than any other total when using two standard casino dice.

    If a process is truly random, the data generated by it should become closer and closer to the expected values as the number of experiments grows without bound.

    The VB pseudo random number generator does a fair job of simulating standard Casino Craps. An application I wrote indicates that it becomes accurate to about 3-5 decimal digits after a few million dice throws, but does not seem to ever get more accurate. This suggests the generator is not the best possible for this purpose. It does a worse job of simulating the overall house percentage than it does in simulating the numbers on each individual die and the totals for two dice. This indicates that the simulated sequence of numbers on each die is not quite the true sequence expected.

    Kedaman: I wonder if there is a pseudo random number generator or a random process which results in a minus infinity to plus infinity range of numbers. I doubt that there is.

    Given a uniform distribution over a finite range, I am pretty sure that the mean is predictable, and that this is true for many other probability distributions. The VB generator is supposed to simulate a uniform distribution of numbers between zero and one. I am not sure if it is possible for the limit value (zero/one) to occur. The expected mean is ½, which seems intuitively obvious, but might be difficult to prove. The following is a reasonable argument, but not really a proof.

    By definition of a uniform distribution, every possible number has the same probability of occurring. Every group of n numbers in small range (EG: .40000 to .40002) should be matched by a similar group of n numbers symmetric to ½ (EG: .59998 to .60000). Thus, each small group of numbers is matched by another group such that the average of the two groups is ½ or close to it.
    Live long & prosper.

    The Dinosaur from prehistoric era prior to computers.

    Eschew obfuscation!
    If a billion people believe a foolish idea, it is still a foolish idea!
    VB.net 2010 Express
    64Bit & 32Bit Windows 7 & Windows XP. I run 4 operating systems on a single PC.

  12. #12
    So Unbanned DiGiTaIErRoR's Avatar
    Join Date
    Apr 1999
    Location
    /dev/null
    Posts
    4,111
    Originally posted by kedaman
    is there any proof for this?
    Yes.

  13. #13
    So Unbanned DiGiTaIErRoR's Avatar
    Join Date
    Apr 1999
    Location
    /dev/null
    Posts
    4,111
    Oh you want proof huh.

    Ok.

    Well.

    To get 'any' random number, a truly, 'random' number.

    You would do something like.

    0-random+random. Which would be 0.

  14. #14
    So Unbanned DiGiTaIErRoR's Avatar
    Join Date
    Apr 1999
    Location
    /dev/null
    Posts
    4,111
    Originally posted by DiGiTaIErRoR
    Oh you want proof huh.

    Ok.

    Well.

    To get 'any' random number, a truly, 'random' number.

    You would do something like.

    0-random+random. Which would be 0.
    Of course this is only 'perfect' if you have infinite random numbers.

    i.e.

    0(-(random*infinity)+(random*infinity))

    Technically infinity minus infinity is undefined. But you get the point. As you get an ever increasing randomness you get an even increasing accuracy towards the mean of the data.

    I hope.

  15. #15
    So Unbanned DiGiTaIErRoR's Avatar
    Join Date
    Apr 1999
    Location
    /dev/null
    Posts
    4,111
    Dim X As Long
    Dim Accuracy As Long
    Dim R As Double
    Accuracy = 1000000
    For X = 1 To Accuracy
    R = R + (Rnd * 500)
    Next
    MsgBox Round(R / Accuracy)

    That'll always report 250.

  16. #16
    transcendental analytic kedaman's Avatar
    Join Date
    Mar 2000
    Location
    0x002F2EA8
    Posts
    7,221
    DiGiTaIErRoR
    Oh you want proof huh.
    I'd appreciate if you or anyone else could find or come up with one
    Guv
    By definition of a uniform distribution, every possible number has the same probability of occurring. Every group of n numbers in small range (EG: .40000 to .40002) should be matched by a similar group of n numbers symmetric to ½ (EG: .59998 to .60000). Thus, each small group of numbers is matched by another group such that the average of the two groups is ½ or close to it.
    your reasoning could probably be backed up with a proof if you have a finite interval, however is there a definition for means for infinite intervals?
    an idea passed my mind, that if you take the generalised integral for f(x)=x, you'd get lim x->+infinity f(x) - lim x->-infinity f(x) = infinity - infinity, which is not defined
    but if you'd take lim t->infinity integ(-t to t, f(x)) then you'd end up with 0, but i think this reasoning is not valid.

    lets assume that there is a pseudo random number generator that does this and that we can test with empirical data, so let it generate a number, which is as presumed, finite, n € R. What is the probability that the next number is larger than this number? What is the probability that abs(n) is smaller than abs(next number)? This would be a trivial problem if the range is finite. Lets calculate the limit with the same formula, and you'll discover that the probability that the next number is larger is 50% and that the abs(next number) is larger is 100%. For instance, let it generate a number n with finite amount of digits, it will always have infinite amount of numbers that have more digits, and only a finite number of digits that are smaller. And theres always infinite amount of numbers that are larger as well as smaller. Not a satisfactory explanation IMO, and i dont think theres a proof..
    Use
    writing software in C++ is like driving rivets into steel beam with a toothpick.
    writing haskell makes your life easier:
    reverse (p (6*9)) where p x|x==0=""|True=chr (48+z): p y where (y,z)=divMod x 13
    To throw away OOP for low level languages is myopia, to keep OOP is hyperopia. To throw away OOP for a high level language is insight.

  17. #17
    Hyperactive Member
    Join Date
    Dec 2001
    Location
    I'm in front of the computer.
    Posts
    270
    This is the code I wrote a while ago for a linear congruential random number generator. Copy and paste into a new class module

    VB Code:
    1. 'A linear congruential random number generator (LCRNG)
    2.  
    3. Option Explicit
    4.  
    5. '||||||||||   CONSTANTS   ||||||||||||||||||||||||||||||||||||||||||||||||
    6.    
    7.     Private Const MaxSize As Long = 2 ^ 22  '= 4194304
    8.         'used for maximum number size and
    9.             'correct fractionalization of random numbers
    10.            
    11.     Private Const MaxSizeTrunc As Long = MaxSize - 1  '= 4194303
    12.         'used to truncate numbers to within maximum size limits
    13.             ' (a mask for binary ands)
    14.            
    15.     Private Const MaxSizeRoot As Long = MaxSize ^ 0.5  '= 2048
    16.         'used in segmentation of large multiplications
    17.        
    18.     Private Const MaxSizeRootTrunc As Long = MaxSizeRoot - 1  '= 2047
    19.         'used as a binary and mask in the segmentation of multiplication
    20.    
    21.     Private Const Multiplier As Long = 3146245
    22.         'multiplied with current random number to get new random numbers
    23.        
    24.     Private Const MultiplierLower As Long = Multiplier And MaxSizeRootTrunc  '= 517
    25.         'pre-calculated lower portion of the number, used in segmentation
    26.             'of large multiplication
    27.    
    28.     Private Const MultiplierUpper As Long = Multiplier \ MaxSizeRoot  '= 1536
    29.         'pre-calculated upper portion of number, same use as above
    30.    
    31.     Private Const AddedNum As Long = 1731
    32.         'added to multiplied numbers to generate new random numbers
    33.    
    34.    
    35. '||||||||||   VARIABLES   |||||||||||||||||||||||||||||||||||||||||||||||||
    36.    
    37.     Private RandomNumber As Long
    38.         'used to store the current random number
    39.    
    40.     Private RandomNumberLower As Long
    41.         'used to store the lower bit portion of the random number
    42.        
    43.     Private RandomNumberUpper As Long
    44.         'used to store the upper bit portion of the random number
    45.    
    46. '||||||||||   PUBLIC METHODS   ||||||||||||||||||||||||||||||||||||||||||
    47.  
    48. Public Sub Init(ByVal Seed As Long)     'used to initialize generator
    49.     RandomNumber = Seed
    50.     NewRand
    51.    
    52.     'used to initialize the random number generator
    53.     'the seed is set as the current random number, from which a
    54.         'new number is immediately generated
    55. End Sub
    56.  
    57.  
    58. Public Function Rand() As Double       'used to retrieve random numbers
    59.     Rand = RandomNumber / MaxSize
    60.         'returns the current random number in decimal format, like Rnd
    61.    
    62.     NewRand
    63.         'generates a new random number for next use
    64. End Function
    65.  
    66.  
    67.  
    68. '||||||||||   PRIVATE METHODS   |||||||||||||||||||||||||||||||||||||||||
    69.  
    70. Private Sub NewRand()   'used to generate a new random number
    71.  
    72.     RandomNumberLower = RandomNumber And MaxSizeRootTrunc
    73.     RandomNumberUpper = RandomNumber \ MaxSizeRoot
    74.        
    75.     'calculates the upper and lower bit portions of the random number
    76.    
    77.  
    78.     RandomNumber = _
    79.         ( _
    80.             AddedNum + _
    81.             ( _
    82.                 ( _
    83.                     ( _
    84.                         ( _
    85.                             RandomNumberLower * MultiplierUpper + _
    86.                             MultiplierLower * RandomNumberUpper _
    87.                         ) _
    88.                         And MaxSizeRootTrunc _
    89.                     ) _
    90.                     * MaxSizeRoot + _
    91.                     RandomNumberLower * MultiplierLower _
    92.                 ) _
    93.                 And MaxSizeTrunc _
    94.             ) _
    95.         ) _
    96.     And MaxSizeTrunc
    97.    
    98.     'generates new random number using complex formula
    99.     'formatting intended to aid interpretation
    100.    
    101.     'Firstly, the upper and lower portions of the current random number
    102.         'are multiplied with their opposite portions of the multiplier.
    103.     'This is truncated to the correct size to prevent overflow.
    104.     'Then, the result is multiplied by the value necessary to raise its
    105.         'position by 11 bits and make space for the actual lower bits.
    106.         '(it was being worked with at lower bit positions to prevent overflow)
    107.     'This is added to the multiplication of the two lower bit portions of
    108.         'the numbers, and the result is truncated to within the actual
    109.         'limit for the numbers. (the upper bit multiplication result causes
    110.             'overflow and would only be truncated anyway)
    111.     'Finally, this is added to the constant specified in declarations, and a
    112.         'final truncation is performed to ensure that the number falls
    113.         'within the correct range.  This new random number will be
    114.         'returned (in the correct format) to the used the next time
    115.         'Rand() is called.
    116. End Sub
    117.  
    118. Private Sub Class_Initialize()
    119.     Init Timer
    120.    
    121.     'automatically initialized on startup in case user forgets to
    122.         'initialize random number generator
    123.        
    124.     'has no adverse effect, nor does it prevent user from initializing
    125.         'again later
    126. End Sub

    Its significantly faster than the intrinsic VB generator, and in the limited tests I've done seems to be comparably random. Beware, though, that it can only generate about 4 million unique random numbers; after that it will repeat. Whether this would cause problems depends on what its being used for.

    Its easy to use; just create a new instance of the class and call class.Rand whenever you need a number between 0 and 1 (just like VB's).
    Alphanos

  18. #18
    VBA Nutter visualAd's Avatar
    Join Date
    Apr 2002
    Location
    Ickenham, UK
    Posts
    4,906

    In Javascript??

    Is there a way to seed the random number generator in Javascript??
    PHP || MySql || Apache || Get Firefox || OpenOffice.org || Click || Slap ILMV || 1337 c0d || GotoMyPc For FREE! Part 1, Part 2

    | PHP Session --> Database Handler * Custom Error Handler * Installing PHP * HTML Form Handler * PHP 5 OOP * Using XML * Ajax * Xslt | VB6 Winsock - HTTP POST / GET * Winsock - HTTP File Upload

    Latest quote: crptcblade - VB6 executables can't be decompiled, only disassembled. And the disassembled code is even less useful than I am.

    Random VisualAd: Blog - Latest Post: When the Internet becomes Electricity!!


    Spread happiness and joy. Rate good posts.

  19. #19
    VBA Nutter visualAd's Avatar
    Join Date
    Apr 2002
    Location
    Ickenham, UK
    Posts
    4,906
    BUMP FROG
    PHP || MySql || Apache || Get Firefox || OpenOffice.org || Click || Slap ILMV || 1337 c0d || GotoMyPc For FREE! Part 1, Part 2

    | PHP Session --> Database Handler * Custom Error Handler * Installing PHP * HTML Form Handler * PHP 5 OOP * Using XML * Ajax * Xslt | VB6 Winsock - HTTP POST / GET * Winsock - HTTP File Upload

    Latest quote: crptcblade - VB6 executables can't be decompiled, only disassembled. And the disassembled code is even less useful than I am.

    Random VisualAd: Blog - Latest Post: When the Internet becomes Electricity!!


    Spread happiness and joy. Rate good posts.

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