PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197
2.0 [RESOLVED] Uptimize my Random Number Generator-VBForums
Results 1 to 16 of 16

Thread: [RESOLVED] Uptimize my Random Number Generator

  1. #1

    Thread Starter
    Fanatic Member coolcurrent4u's Avatar
    Join Date
    Apr 2008
    Location
    *****
    Posts
    989

    Resolved [RESOLVED] Uptimize my Random Number Generator

    Hello guys,

    Am using a random number generator in a loop
    I used this function to generate random number in vb.net and it worked fine

    vb Code:
    1. '//Generate RandomNumber
    2.     Private Function RandomNum(ByVal Lower As Long, _
    3.     ByVal Upper As Long) As Long
    4.         Randomize(Timer)
    5.         RandomNum = Rnd() * (Upper - Lower + 1) + Lower
    6.     End Function

    Converting to c# made is extremely slow

    c# Code:
    1. ////Generate RandomNumber
    2.         private int RandomNum(int Lower, int Upper)
    3.         {
    4.             System.Random RandNum = new System.Random();
    5.             int MyRandomNumber = RandNum.Next(Lower, Upper);
    6.             System.Threading.Thread.Sleep(100);// this line makes the random generator give unique value
    7.             return MyRandomNumber;
    8.         }

    Please can you help me uptimize it?
    Programming is all about good logic. Spend more time here


    (Generate pronounceable password) (Generate random number c#) (Filter array with another array)

  2. #2
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,020

    Re: Uptimize my Random Number Generator

    Dont create a new Random object each time the function is called.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  3. #3

    Thread Starter
    Fanatic Member coolcurrent4u's Avatar
    Join Date
    Apr 2008
    Location
    *****
    Posts
    989

    Re: Uptimize my Random Number Generator

    Hello, thanks, so how do i do that.
    perhaps you could give me some code.
    Last edited by coolcurrent4u; May 31st, 2010 at 07:09 AM. Reason: typo
    Programming is all about good logic. Spend more time here


    (Generate pronounceable password) (Generate random number c#) (Filter array with another array)

  4. #4
    PowerPoster RhinoBull's Avatar
    Join Date
    Mar 2004
    Location
    New Amsterdam
    Posts
    24,135

    Re: Uptimize my Random Number Generator

    Also, why do you need Sleep in there?
    Code:
        public partial class Form1 : Form
        {
            System.Random RandNum = new System.Random();
    
            private int RandomNum(int Lower, int Upper)
            {
                int MyRandomNumber = RandNum.Next(Lower, Upper);
                return MyRandomNumber;
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                textBox1.Text = RandomNum(1, 100).ToString();
            }
        }

  5. #5
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,020

    Re: Uptimize my Random Number Generator

    The reason he was using Sleep is that the random function uses the current time as a seed, and thus calling Next too fast will return identical values.
    This is all avoided by using one random instance only, as it'll always return an unique value even though its Next function is called in a tight loop.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  6. #6
    Frenzied Member avrail's Avatar
    Join Date
    Mar 2006
    Location
    Egypt, Cairo
    Posts
    1,221

    Re: Uptimize my Random Number Generator

    hey,
    Code:
    System.Threading.Thread.Sleep(100);// this line makes the random generator give unique value
    who said this will generate a unique value?
    You Don't Have to Rate Me.
    I'm Not a Civilized Man I'm the Civilization it self
    White or Black, Living or Dieing and 0 or 1 that's MY life
    iam an Object in Object Oriented Life
    my blog : http://refateid.blogspot.com/
    twitter :@avrail
    010011000111010101110110001000000100110101111001001000000101000001100011

  7. #7
    PowerPoster RhinoBull's Avatar
    Join Date
    Mar 2004
    Location
    New Amsterdam
    Posts
    24,135

    Re: Uptimize my Random Number Generator

    Quote Originally Posted by Atheist View Post
    The reason he was using Sleep is that the random function uses the current time as a seed, and thus calling Next too fast will return identical values...
    Never saw it happened before, although I don't use random numbers often.

  8. #8

    Thread Starter
    Fanatic Member coolcurrent4u's Avatar
    Join Date
    Apr 2008
    Location
    *****
    Posts
    989

    Re: Uptimize my Random Number Generator

    Quote Originally Posted by RhinoBull View Post
    Also, why do you need Sleep in there?
    Code:
        public partial class Form1 : Form
        {
            System.Random RandNum = new System.Random();
    
            private int RandomNum(int Lower, int Upper)
            {
                int MyRandomNumber = RandNum.Next(Lower, Upper);
                return MyRandomNumber;
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                textBox1.Text = RandomNum(1, 100).ToString();
            }
        }
    This gives identical values in a for loop. That is why i was using that line

    c# Code:
    1. System.Threading.Thread.Sleep(100);

    And can i place two class in one file?

    i had to place you solution in a form to test it
    Programming is all about good logic. Spend more time here


    (Generate pronounceable password) (Generate random number c#) (Filter array with another array)

  9. #9

    Thread Starter
    Fanatic Member coolcurrent4u's Avatar
    Join Date
    Apr 2008
    Location
    *****
    Posts
    989

    Re: Uptimize my Random Number Generator

    I used a tool online to convert my vb.net function to c#

    i got this
    c# Code:
    1. private long RandomNum(long Lower, long Upper)
    2. {
    3.     VBMath.Randomize(Timer);
    4.     return VBMath.Rnd() * (Upper - Lower + 1) + Lower;
    5. }

    c# can't find these functions VBMath.Randomize,Timer,VBMath.Rnd

    any help
    Programming is all about good logic. Spend more time here


    (Generate pronounceable password) (Generate random number c#) (Filter array with another array)

  10. #10

    Thread Starter
    Fanatic Member coolcurrent4u's Avatar
    Join Date
    Apr 2008
    Location
    *****
    Posts
    989

    Re: Uptimize my Random Number Generator

    ok Guys i found the solution

    At the top of my class where i place class member variable i do this

    c# Code:
    1. private static Random rnd = new Random(Environment.TickCount);

    And my new function

    c# Code:
    1. //Generate RandomNumber
    2.         private int RandomNum(int Lower, int Upper)
    3.         {
    4.                  
    5.             return rnd.Next(Lower, Upper);
    6.            
    7.         }

    Thanks for all you support
    Programming is all about good logic. Spend more time here


    (Generate pronounceable password) (Generate random number c#) (Filter array with another array)

  11. #11
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,020

    Re: [RESOLVED] Uptimize my Random Number Generator

    Well, in a nutshell thats just what I wrote in my first post.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  12. #12
    Frenzied Member avrail's Avatar
    Join Date
    Mar 2006
    Location
    Egypt, Cairo
    Posts
    1,221

    Re: [RESOLVED] Uptimize my Random Number Generator

    great method with out thread.sleep
    You Don't Have to Rate Me.
    I'm Not a Civilized Man I'm the Civilization it self
    White or Black, Living or Dieing and 0 or 1 that's MY life
    iam an Object in Object Oriented Life
    my blog : http://refateid.blogspot.com/
    twitter :@avrail
    010011000111010101110110001000000100110101111001001000000101000001100011

  13. #13
    PowerPoster
    Join Date
    Apr 2007
    Location
    The Netherlands
    Posts
    5,070

    Re: [RESOLVED] Uptimize my Random Number Generator

    Just a little clarification. When you create a new Random object, it must use a seed value to determine its sequence of random numbers. If no seed value is given, the system time is used (which is sufficient in most cases).

    If you create multiple Random objects all with the same seed value, then they will generate the exact same sequence of "random" numbers. This is also why these random numbers are called "pseudo-random". They aren't absolutely random, but they are generated using some formula and the seed value. If you know the formula and the seed value, you can generate the exact same sequence of numbers.

    So, the Random object doesn't just generate a single value, it can generate a whole sequence of values. You get the next number in the sequence using the Next method.

    If you create new Random object every time you need a random number, and then call that method multiple times in a loop, then chances are that your loop will run so fast that the system time (= seed value for ALL random objects created) will be the same for at least 4 or 5 iterations. Hence, these Random objects all generate the same sequence of numbers, and because you are only using the very first every time, you will see that they generate the same "random" numbers.

    Adding a short sleep to the loop will make it work, because the seed value (system time) is now no longer the same for two iterations. The sequence of random numbers (of which you are still using only the first) is different each time, and you get different numbers. However, it is not a very good solution, because as you have noticed, adding a sleep of 0.1 second every iteration will slow down your loop a LOT. A mere 10 iterations will make it take a whole second, where 10 iterations usually run in a few microseconds. That's a factor 1.000.000 slower, for absolutely no reason.

  14. #14

    Thread Starter
    Fanatic Member coolcurrent4u's Avatar
    Join Date
    Apr 2008
    Location
    *****
    Posts
    989

    Re: [RESOLVED] Uptimize my Random Number Generator

    Quote Originally Posted by NickThissen View Post
    Just a little clarification. When you create a new Random object, it must use a seed value to determine its sequence of random numbers. If no seed value is given, the system time is used (which is sufficient in most cases).

    If you create multiple Random objects all with the same seed value, then they will generate the exact same sequence of "random" numbers. This is also why these random numbers are called "pseudo-random". They aren't absolutely random, but they are generated using some formula and the seed value. If you know the formula and the seed value, you can generate the exact same sequence of numbers.

    So, the Random object doesn't just generate a single value, it can generate a whole sequence of values. You get the next number in the sequence using the Next method.

    If you create new Random object every time you need a random number, and then call that method multiple times in a loop, then chances are that your loop will run so fast that the system time (= seed value for ALL random objects created) will be the same for at least 4 or 5 iterations. Hence, these Random objects all generate the same sequence of numbers, and because you are only using the very first every time, you will see that they generate the same "random" numbers.

    Adding a short sleep to the loop will make it work, because the seed value (system time) is now no longer the same for two iterations. The sequence of random numbers (of which you are still using only the first) is different each time, and you get different numbers. However, it is not a very good solution, because as you have noticed, adding a sleep of 0.1 second every iteration will slow down your loop a LOT. A mere 10 iterations will make it take a whole second, where 10 iterations usually run in a few microseconds. That's a factor 1.000.000 slower, for absolutely no reason.
    Thanks for the info.

    I know adding sleep makes the random number unique, but i can sacrifice the time. Note that i generate each seed each time i call the class.

    IMO i think this would make each set of random numbers as unique as possible. You could run a test to prove it wrong or something.

    I onces red in a math book that there is no way of generating true random number using a computer.

    So the environment/programming language is using some sort of formula as you said.

    Am open to suggestion and correction.

    Note that i use the word "Optimize" in the thread name.
    Programming is all about good logic. Spend more time here


    (Generate pronounceable password) (Generate random number c#) (Filter array with another array)

  15. #15
    PowerPoster
    Join Date
    Apr 2007
    Location
    The Netherlands
    Posts
    5,070

    Re: [RESOLVED] Uptimize my Random Number Generator

    First of all, the term "unique" is not really appropriate. Unique usually means that you want to generate a set of random numbers without repeating any numbers (so for example 41802 is a set of 5 unique numbers, while 41804 is not). Adding a sleep will not make your random number generators generate unique random numbers.

    Now, you say that you can sacrifice the time, yet in the very first post (presumably the reason you made this post in the first place) you say that your code has suddenly slowed down. Of course it has, you are doing nothing for 0.1 second every iteration!

    Whether using a single Random object or using multiple Random objects with different seed values create "more random" numbers is hard to determine. A true random number generator generates each number with equal probability, but even after generating millions of numbers you'll always see a few numbers that have been chosen more times, simply due to chance.

    You cannot generate a true random number using computer algorithms, no, but you can (well, this is up for debate really) using a computer. For example, you could use the mouse movements to determine a random number, or you could measure the temperature of your CPU very accurately and use that, or ... You'd have to use something that is outside of anyone's control.
    Of course, you can argue that even the mouse movements someone makes aren't random, as he is actively controlling the mouse, but at least there is no way to predict those movements, so you cannot predict the random numbers either. If you know the formula and seed value for any random number generator using an algorithm, you can predict all the numbers it will spit out simply by applying the formula.

  16. #16

    Thread Starter
    Fanatic Member coolcurrent4u's Avatar
    Join Date
    Apr 2008
    Location
    *****
    Posts
    989

    Re: [RESOLVED] Uptimize my Random Number Generator

    NickThissen what you said is true, to some extent!

    My app generates random number in sets, eg like 10, 20 etc, so it is crucial that the random generator generation of numbers is fast and random.

    There is a problem with this random generation though. if for example i pass 1 as min and 10 as max, and i loop 10 times. I'd expect that no number repeats itself, bu this is not true some numbers are never used while other repeat at least once or never.

    In an application where it is crucial that no number repeat, it then means i'll use an alternative way. This is the algorithm.

    Code:
    Generate numbers from min to max, and sore in array
    Shuffle the array
    pick numbers from the lowest value to the largest
    loop until exhausted
    This will ensure that at least each number is used once, only unique is some cases not all. In a situation where only a single number is required, the this system will fail.

    Am still working on some algorithm, and will post it here when i finish.
    Programming is all about good logic. Spend more time here


    (Generate pronounceable password) (Generate random number c#) (Filter array with another array)

Posting Permissions

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



Featured


Click Here to Expand Forum to Full Width