A simple question on random number generation?

Hi,
This is a rather simple question and shows my newbieness quite blatantly!
I'm trying to generate a random number in a part of a test I have.
So, I have a little method which looks like this:
public int getRandomNumber(int number){
        Random random = new Random(number);
        return random.nextInt(number);
    }And in my code I do int random = getRandomNumber(blah)...where blah is always the same number.
My problem is it always returns the same number. What am I missing here. I was under the impression that nextint(int n) was supposed to generate the number randomly!! Obviously I'm doing something wrong or not using the correct thing. Someone please point out my stupidity and point me in the right direction? Ta

I think the idea is that Random will generate the same pseudo-random sequence over and over if you don't supply a seed value. (The better to debug with, my dear.) When you're ready to put an app into production, the seed value should be the current system time in milliseconds to guarantee a new sequence with each run.
Do indeed move Random outside the loop. Think of it like a number factory - instantiate it once and let it pump out the random values for you as needed.

Similar Messages

  • What algorithm does Excel 2010 use for Pseudo Random Number Generation (MT19937?)

    Does Excel 2010+ use the Mersenne Twister (MT19937) algorithm for Pseudo Random Number Generation (PRNG), implemented by the RAND() function?
    This has been a nagging question for some time now, with "hints" that it indeed does.  However, a relatively thorough search turns up no definitive documentation.  The most direct indication is perhaps given by Guy Melard [Ref 9] where
    he tests Excel 2010's RAND() function using the Crush battery of tests in TestU01 by L'Ecuyer & Simard.  Melard references a "semi-official" indication that Microsoft did indeed implement MT19937 for the RAND() function in
    Excel 2010, but this reference no longer seems to be available. http://office.microsoft.com/enus/excel-help/about-solver-HP005198368.aspx?pid=CH010004571033.
    The other references below [Ref 1-10] document the history of the statistical suitability of the PRNG and probability distributions in various versions of Excel.  This includes the Wichmann-Hill PRNG implementations supposedly (arguably) used in
    Excel 2003 & 2007 for random number generation.  But still, we have no answer as to which PRNG algorithm is used in
    Excel 2010 (and 2013 for that matter).
    Microsoft indicates that RAND() has been improved in Excel 2010; Microsoft states, "...and the RAND function now uses a new random number algorithm." (see https://support.office.com/en-ca/article/Whats-New-Changes-made-to-Excel-functions-355d08c8-8358-4ecb-b6eb-e2e443e98aac). 
    But no details are given on the actual algorithm.  This is critical for Monte Carlo methods and many other applications.
    Any help would be much appreciated. Thanks.
    [Ref 1] B. McCullough, B. Wilson.  On the Accuracy of Statistical Procedures in Microsoft Excel 97. 
    Computational Statistics & Data Analysis. Vol. 31 No. 1, pp 27-37. July 1999.
    http://users.df.uba.ar/cobelli/LaboratoriosBasicos/excel97.pdf
    [Ref 2]L. Knüsel.  On the accuracy of the statistical distributions in Microsoft Excel 97. Computational Statistics & Data Analysis. Vol. 26 No. 3, pp 375-377. January 1998.
    http://www.sciencedirect.com/science/article/pii/S0167947397817562
    [Ref 3]B. McCullough, B. Wilson.  On the Accuracy of Statistical Procedures in Microsoft Excel 2000 and Excel XP. 
    Computational Statistics & Data Analysis. Vol.40 No. 4, pp 713-721. October 2002.
    https://www.researchgate.net/publication/222672996_On_the_accuracy_of_statistical_procedures_in_Microsoft_Excel_2000_and_Excel_XP/links/00b4951c314aac4702000000.pdf
    [Ref 4] B. McCullough, B. Wilson.  On the Accuracy of Statistical Procedures in Microsoft Excel 2003. 
    Computational Statistics & Data Analysis. Vol.49. No. 4, pp 1244-1252. June 2005.
    http://www.pucrs.br/famat/viali/tic_literatura/artigos/planilhas/msexcel.pdf
    [Ref 5] L. Knüsel. On the accuracy of statistical distributions in Microsoft Excel 2003. Computational Statistics & Data Analysis, Vol. 48, No. 3, pp 445-449. March 2005.
    http://www.sciencedirect.com/science/article/pii/S0167947304000337
    [Ref 6]B. McCullough, D.Heiser.  On the Accuracy of Statistical Procedures in Microsoft Excel 2007. 
    Computational Statistics & Data Analysis. Vol.52. No. 10, pp 4570-4578. June 2008.
    http://users.df.uba.ar/mricci/F1ByG2013/excel2007.pdf
    [Ref 7] A. Yalta. The Accuracy of Statistical Distributions in Microsoft<sup>®</sup> Excel 2007. Computational Statistics & Data Anlaysis. Vol. 52 No. 10, pp 4579 – 4586. June 2008.
    http://www.sciencedirect.com/science/article/pii/S0167947308001618
    [Ref 8] B. McCullough.  Microsoft Excel’s ‘Not The Wichmann-Hill’ Random Number Generators. Computational Statistics and Data Analysis. Vol.52. No. 10, pp 4587-4593. June 2008.
    http://www.sciencedirect.com/science/article/pii/S016794730800162X
    [Ref 9] G. Melard.  On the Accuracy of Statistical Procedures in Microsoft Excel 2010. Computational Statistics. Vol.29 No. 5, pp 1095-1128. October 2014.
    http://homepages.ulb.ac.be/~gmelard/rech/gmelard_csda23.pdf
    [Ref 10] L. Knüsel.  On the Accuracy of Statistical Distributions in Microsoft Excel 2010. Department of Statistics - University of Munich, Germany.
    http://www.csdassn.org/software_reports/excel2011.pdf

    I found the same KB article:
    https://support.microsoft.com/en-us/kb/828795
    This was introduced (according to the article) in Excel 2003. Perhaps the references in notes 2 and 3 might help.
    The article describes combining the results of 3 generators, each similar to a Multiply With Carry (MWC) generator, but with zero carry. MWC generators do very well on the Diehard battery of randomness tests (mentioned in your references), and have
    very long periods. But using zero carry makes no sense to me.
    Combining the three generators only helps if the periods of the 3 are relatively prime (despite what the article implies). Then the period of the result will be the product of the 3 periods. But without knowing the theory behind these generators, I have
    no idea what the periods would be. The formulas for MWC generators fail here.
    Richard Mueller - MVP Directory Services

  • True Random number generation in OSX

    Hi there,
    I have been trying to find some information on how to access the Intel Random number generation hardware on my Mac.
    First I would like to understand which models currently offer this, second I would like to know if there is some library available I could use from either C or any other language, even from Applescript would be good for me.
    Thanks in advance.

    Perhaps these links help:
    http://www.intel.com/software/products/mkl/docs/mklnotes_mac.htm
    (keep in mind that apple typically discourages targeting specific hardware...)
    http://forums.macosxhints.com/showthread.php?t=46359
    http://www.mactricksandtips.com/2008/03/apple-script-random-number-generator.htm l

  • Problem with random number generation

    hey forum, i wonder if anyone can help me out with a small problem with my university coursework (yep its homework!!!)
    heres my problem, i am writing one of them 8 puzzle problems (the one based around sam lloyds 15 puzzler), i can successfully generate one random sequence of numbers with no duplicates, but whenever i call the random method again it keeps producing the same results
    heres the code
    in my main class file
    if(e.getSource() == randomButton) {
          new RandomPuzzle();
          System.out.println(random.randState);
          //startStateString = new RandomPuzzle();
    }heres my number generator class file
    import java.util.Random;
    import java.io.*;
    public class RandomPuzzle
         /** Base Random number generator */
        Random rn = new Random();
        /** Puzzle holder */
        byte b[];
        long number = 0;
        String randState = "";
        /** Default constructor */
        public RandomPuzzle() {
            rn.setSeed(number);
            b = new byte[9];
            randState = randomString();
        /** Provide range for generation */
        public int rand(int lo, int hi) {
            int n = hi - lo + 1;
            int i = rn.nextInt() % n;
            if (i < 0)
            i = -i;
            return lo + i;
        /** Set size for array */
        public int rand( int hi){
            int n = hi;
                return n;
        /** Check for duplicate values within the same configuration */
        boolean valueExists( byte value ) {
            int i = b.length;
            boolean exists = false;
            for( int j = 0; j < i; j++ ){
                if( b[j] == value )
                    exists = true;
            return exists;
        /** returns the actual string */
        public String randomString(int lo, int hi) {
            int n = rand( 9 );
            //boolean valueEntered = false;
            for (int i = 0; i < 9; i++) {
                boolean valueEntered = false;
                byte temp = (byte)rand('0', '8');
                while( valueEntered == false ) {
                    if( !valueExists( temp ) ) {
                         b[i] = temp;
                         valueEntered = true;
                    else
                        temp = (byte)rand('0', '8');
            return new String(b, 0);
        /** calls above function */
        public String randomString() {
            return randomString(0, 8);
    }i've tried for hours to work this out, but i am stumped. if anyone can point me in the right direction, maybe point out the problem code and give one or two tips i would be forever in your debt
    thanx in advance
    korbitz

    thanx for the help paulcw, but when i removed the seed code it done the same
    but i added this to my main class and now it works fine
    if(e.getSource() == randomButton) {
                   RandomPuzzle temp = new RandomPuzzle();
                   System.out.println(temp.randState);
                   //startStateString = new RandomPuzzle();
              }thanx again for your help

  • Random number generation that sticks

    Hello,
    I would appreciate any help with the appropriate JavaScript to generate a random 8 digit number XXXX-XXXX on a form when the user starts to enter data. This number would need to be permanent so that it can be used as a tracking identifier later.
    Thanks for looking.
    Dawson

    If you're using Oracle8i, you can use the new SAMPLE clause in the FROM clause of the SELECT statement to query a random sample from a single table. Otherwise, just write a simple random number generator in PL/SQL (see any good algorithm book under the topic "Psuedorandom number generator"). You need to understand a bit about statistics, if being "truly" random is important, to use these tools.

  • Random Number generation within BPEL

    I am trying to embed a java-exec and trying to generate random number using a code as follows:
    int ranNumber1 = (int)(Math.random()*1000000000000000.0);
    int ranNumber2 = (int)(Math.random()*1000000000000000.0);
    setVariableData("RanNumber1",new Integer(ranNumber1));
    setVariableData("RanNumber2",new Integer(ranNumber2));
    I always get the same value for ranNumber1 and for ranNumber2 and for every instance, the value seems to be the same.. Actually the value generated is 2147483647 always..
    Am I doing anything wrong? Can anyone clarify here, please...

    // construct a bigdecimal, exaclty lenght'd 10 digits
    BigDecimal z = new BigDecimal("10000000000");
    // multiply it randomly (random returns something between 0 and 1)
    z = z.multiply(new BigDecimal(Math.random()));
    // and use the rounding ..
    BigInteger big = z.toBigInteger();
    is one option, I guess not the nicest but working ..

  • Random number generation in numbers

    I cannot find out how to create a random number colum. It ios very easy on Excell ,but my attempts on numbers have been frustrating. I look at the instructions, but when I click on formulas it doesnt show the whole list.

    Clark,
    You might find it convenient to have Formulas and Functions Help open as you work on your document. It has a little different layout than the Function Browser.
    Jerry

  • Random number generation with format 18XX88YYYYY

    I have been tryig to generate random numbers having
    format 18xx88yyyyy
    here
    18 followed by two random number then 88 followed by five random number. here 18 and 88 are fixed at location one,two,five and sixth position.
    but I am unable to get the logic .
    So please help
    Thanx
    Achyot

    After changing the column from number to varchar2 I am getting my correct result...
    create or replace function generateRandom return varchar2 is
    random varchar2(11);
    begin
    SELECT '18'|| lpad(ROUND (DBMS_RANDOM.VALUE (0, 100)),2,'0')|| '88'|| lpad(ROUND (DBMS_RANDOM.VALUE (0,
    100000)),5,'0')
    into random FROM DUAL;
    return random;
    end;
    create or replace procedure insertRandom is
    getNum varchar2(11);
    x number(3);
    cnt number;
    cursor checkpk is
    select random_no n from rand_no;
    begin
    cnt:=0;
    while (cnt<3054) loop
    x:=0;
    getNum:=generateRandom;
    for pkcheck in checkpk loop
    if getNum=pkcheck.n then
    x:=x+1;
    end if;
    end loop;
    if x=0 then
    insert into rand_no values(getNum);
    end if;
    select count(*) into cnt from rand_no;
    end loop;
    commit;
    end insertRandom;
    output:
    RANDOM_NO
    18388817929
    18658842315
    18028870847
    18898822037
    18678818255
    18248878003
    18558852407
    18878870907
    18998892135
    18538876212
    18908820740
    Thanx you everyone...

  • Need Random "Number" Generation

    Hi...
    Need an easy way to generate a random "number" from an ABAP program... that is a combination of numbers and alphabetic characters.
    Is there a Function Module I did not find?
    Currently using Function module 'QF05_RANDOM_INTEGER' but this only generates a number.
    Thanks for your insights !
    Dave...

    Hi,
    I wrote a little method to generate a random number between 1 and 100 (can be modified to allow bigger range of numbers).  The code is below...  It basically gets a timestamp into a field of type timestampl (note the letter L at the end of the type).  The method signature consists of a single returning parameter called RANDOM_NUMBER (type I).  After much testing, the random sequence of numbers is extremely varied (even without a seed).
    Since 'QF05_RANDOM_INTEGER' already exists, then my method is not needed here, but I thought I'd include it in this thread since the topic was brought up.
    Cheers,
    James G.
    METHOD GENERATE_RANDOM_NUMBER .
      DATA:
        delay_cnt     TYPE i,
        lc_ran_seed   TYPE p,
        lc_time       TYPE timestampl,
        ran_num       TYPE p DECIMALS 7.
    * Get the long time stamp (nano second level)
      GET TIME STAMP FIELD lc_time.
    * Get the decimal part of the time stamp and shift it so that only the
    * last decimal values are used (i.e. the smallest unit of time)
      ran_num = frac( lc_time ).
      ran_num = ran_num * 10000.
    * Perform a delay with a varying length of time so that the next time
    * stamp will be more "random" if the method is called multiple times
    * (e.g. if called in a do loop to generate many random numbers)
      delay_cnt = ran_num * 2.
      DO delay_cnt TIMES. ENDDO.
    * Get the decimal part of the shifted time stamp, multiply it by 100 to
    * shift it to the left 2 decimal places, and add 1 to the result.
      ran_num = frac( ran_num ).
      lc_ran_seed = ( ran_num * 100 ) + 1.
      random_number = lc_ran_seed.
    * If the number generated is not between 1 and 100, then try again.
      IF random_number IS INITIAL OR random_number < 1
                                  OR random_number > 100.
        CALL METHOD me->generate_random_number
          RECEIVING
            random_number = random_number.
      ENDIF.
    ENDMETHOD.

  • Random Number Generation

    According to the documentation, java makes random numbers with this algorithm.
    synchronized protected int next(int bits) {
           seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);
           return (int)(seed >>> (48 - bits));
    }The purely mathematical concept is this:
    Xn = (Xn-1 * constant1  + constant2) % constant3.In other words, to find a new number, we multiply the old number with a constant, add it to another constant, and then do modulus constant3 on the sum.
    That's okay, it's the java-specific implementation im wondering a little about.
    I've also understood that you can replace (sum % constant3) with (sum % (constant3 -1)), if constant3 is a power of 2.
    But:
    1. The function returns an integer, but still, the seed is a long.
    Why? Is it to prevent (seed * 0x5DEECE66DL + 0xBL) from overflowing?
    If that's the case, wouldnt that mean this function DEPENDS on long being longer than an integer?
    2.Why do they choose exactly (1L << 48)) as modulus?
    (1L << 48) ) means we got a 1, and 48 zeroes behind it? So the modulus is a power of 2 ^ 48, using 49 bits? And then we just subtract 1 to get to use the &, instead of the % operator, for performance reasons?
    Doesent this mean that this function depends on a long being atleast 64bits?
    What's the function of the remaining bits? (since we're just using 48 / 49 bits, during the computation).
    Are they used as a "overflow-buffer"?
    Edited by: Drogin on Jun 28, 2009 5:33 PM
    Edited by: Drogin on Jun 28, 2009 5:33 PM

    Drogin wrote:
    1. The function returns an integer, but still, the seed is a long.
    Why? Is it to prevent (seed * 0x5DEECE66DL + 0xBL) from overflowing?I don't see how it would prevent it overflowing or why it would matter.
    If that's the case, wouldnt that mean this function DEPENDS on long being longer than an integer?A lot in java depends on the JLS being followed.
    2.Why do they choose exactly (1L << 48)) as modulus?
    (1L << 48) ) means we got a 1, and 48 zeroes behind it? Perhaps because this function will only generate up to 32-bit and 48-bits is more than enough.
    So the modulus is a power of 2 ^ 48, using 49 bits?No, the operation specificly limits the value to be 48-bits long.
    Doesent this mean that this function depends on a long being a tleast 64bits?At least 48-bits I imagine, but it is 64-bits and always will be.
    And then we just subtract 1 to get to use the &, instead of the % operator, for performance reasons?Perhaps, jvms are smarter than they were whent he code was written so you might not need to do this now.
    What's the function of the remaining bits? (since we're just using 48 / 49 bits, during the computation).They don't appear to be used.
    Are they used as a "overflow-buffer"?It wouldn't matter if this function overflowed, so I wouldn't think so.
    In my experience, often in simple operations like this, the bit in the middle of the number are the most random. i.e. they have slightly better statistical properties.
    It is likely that people played around with the three numbers in this equation until they got a random distribution they were happy with.

  • Random Number Generation Within An Object

    Hi, im trying to create an Arraylist containing 10 objects from class Child (see below). Each Child has an age between 1 and 30 which should be randomly generated but for some reason each one is the same. However when i use the BlueJ debugger and step through the program it creates appropriately random numbers so im assuming the problem is with the speed at which the code is run. Any ideas as to how i can combat this? Heres the code:
    Main Class:
    public static void main(String args[]) {
    int index = 0;
    while(index < 10) {
              test = new Child();
              int age = test.getAge();
              schoolbus.add(test);
              System.out.println((index + 1) + ": " + age);
              index++;
    Child Class:
    public class Child {
    private int age;
    Random r = new Random();
    public Child() {
    age = r.nextInt(30);
    public int getAge() {
    return age;
    Thanks, Nick

    You're creating 10 new Random() objects within the same millisecond, this gives them all the same seed and they produce the same first number. You could produce all ages from the same Random() outside the child class and set the age within the child's constructor e.g.
    //snip
    //This bit refers to the Main class
    Random r = new Random();
    while(index < 10) {
    test = new Child(r.nextInt(30));
    //snip- Mr K

  • Mutlivariate normal distributed random number generation

    I am trying to use the random 'norm' function in Mathscript to randomly sample multivariate normal distribution (trivariate to be exact).  I haven't worked much with Mathscript so I am fishing for a little help.
    In the ideal world the code would function like MVNRND from Matlab
    http://www.mathworks.com/access/helpdesk/help/toolbox/stats/index.html?/access/helpdesk/help/toolbox...://www.google.com/search?hl=en&client=firefox-a&rls=org.mozilla:en-USfficial&hs=LcH&ei=HlpuSqOmCYPYM5rkveQC&sa=X&oi=spell&resnum=0&ct=result&cd=1&q=mvnrnd+mathworks&spell=1 
    Where the inputs are 
    (1) the means
    (2) the variance-covariance matrix
    (3) the number of samples (cases)
    Is this possible with the random 'norm' function in mathscript?

    It turns out there are several possible solutions to this problem using LabVIEW
    (1) The TSA vector normal distribution VI in the LV 8.6 Advanced Signal Processing toolkit seems apporpriate, but I do not have the funds to upgrade.
    (2) The 'mvnrnd' function could be called in a Matlab script node. This would require the target computers (once I compile this code as executable) would be required to have Matlab installed; however, one respondant to the thread below suggested that it might run on a Matlab run-time engine.  
     http://forums.ni.com/ni/board/message?board.id=170&message.id=427321#M427321
    (3) It turns out that Scilabs function grand 'mn' does the same thing as 'mvnrnd' in Matlab and can be invoked using a scilab script node package that can be downloaded and installed.  Scilab is freeware, so it is not alot to ask potential users of my Labview executable to download and install this.
    The block diagram is shown below.  FYI all of this is for bootstrapping uncertainties.
    Attachments:
    Sclilab grand 'mn' .pdf ‏26 KB
    Scilab grand 'mn' front panel.pdf ‏107 KB

  • Five Random Number Generation between numbers 10-20

    I want to generate 5 random numbers (U32) between a range of 120 and 180 with equal distribution. Can i do it? I tried using white noise generation VI, but it gives numbers from [-a,a].
    Thanks in advance.

    stevem181 wrote:
    Note that the 120 and 180 values occur about half as often as the other values.
    To correct that flaw, multiply by 61 and round to -infinity. For example like this:
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    RandomRange.png ‏17 KB

  • Simple Question about Serial Number

    I'm really sorry if this is amateur, but earlier I bought a serial number on-line for Pages and it says it was electronically delivered. (I have a paper to write tonight). But I can only find one serial-number-looking-thing within the two emails they sent me and when I type it in to Pages it says it's an incorrect number. Am I looking in the wrong place? How long is the number usually? The only reason why I'm asking on here is because the number to call for support closes at 8:00 pm and it's 8:30. I'm desperate.

    First of all, I don't think you can buy a serial number for Pages alone -- you have to buy a serial number for iWork. Assuming you are talking about iWork08, my serial number has this makeup:
    XXXX-XXXX-XXXX-XXXX-XXXX-XXX
    where "X" represents an alpha-numeric character. All alpha characters are in upper case.

  • Random Number Generation - A die

    Hey everyone, my program uses a normal 6-faced die. Ive got the following two methods to do this: Is other ways?
    METHOD 1:
    // public static int dice(){
    // int num = 0;
    // while(num == 0)
    // num = (int)(Math.random()*7);
    // return num;
    METHOD 2:
    // public static int dice(){
    // int num = 0;
    // while (num==0)
    // num = rand.nextInt(7);
    // System.out.println("Num " + num );
    // return num;

    Random random = new Random();
    public int rollDice()
    return random.nextInt(6)+1;
    }

Maybe you are looking for

  • Count rows from several tables

    hello, im trying to count row from multiple tables for example i need the select statement to produce the following table_name count table1 5 table2 6 table3 3 i came up with the following script but it counts the number of tables i have select objec

  • Add a photo from iPhoto as album artwork...?

    Hi, Lovely wonderful iTunes Match has scrubbed the artwork of all of my bands albums, which is nice. I have all the album artwork as jpegs in iphoto. How come I can't add a picture as artwork? All I get is the finder box come up when I click add, fro

  • Use method in constructor?

    Is it possible to call a method in a constructor if that method belongs to the same class? Will there be problems calling the method since the object hasn't been completely created yet? Example code: Class Foo   // constructor public Foo()    method

  • Will my itunes/app store credit transfer over when I change countries?

    I currently have about $40 on my account, do I have to spend it all before I move (from US to Canada)? Or will it transfer over? Thanks for the help!

  • If export an image from Lightroom 5 to Photoshop and make changes

    after export an image from Lightroom 5 to Photoshop and make changes to this image and then save in Photoshop as a tiff it does not show up in the original folder in Lightroom after exiting Photoshop