Create a congruential random numbers

I want to create a congruential random numbers generator in java:
Below is the formula for it.
ri+1=(a*ri+b) mod M .
How can I use Math class for this?

Your guess w.r.t. a and b being constants is right. An ordinary multiple congruence random number
generator simply looks as you described:
x[n+1]= (a*x[n]+b)%M
But there's a bit more to it: a and b have to be relatively prime, i.e. gcd(a, b) == 1 and the same counts
for both a and b w.r.t. M, i.e. gcd(a, M) == 1 and gcd(b, M) == 1. Only then the 'cycle length' of your
generator will be maximal. In practice M is a power of two (2^32 comes to mind). Here's some code:public class MGRNG {
   private int a, b, M;
   private int seed;
   // ctors
   MGRNG(int a, int b, int M) { this(a, b, M, 1); }
   MGRNG(int a, int b, int M, int seed) {
      this.a= a;
      this.b= b;
      this.M= M;
      this.seed= seed;
   // next pseudo random number
   public int next() {
      seed= (a*seed+b)%M;
      return seed;
} kind regards,
Jos

Similar Messages

  • Program to create random numbers in plsql

    How do we Write a program to create random numbers.
    Thanks

    No need to - we have DBMS_RANDOM :)

  • Create Random Numbers using OLE Randomize and RND

    Hi,
    I've managed to create an excel spreadsheet by creating an object of type EXCEL.APPLICATION. I've also managed to rename the worksheet tabs, move from one tab to another as well as fill certain cells with numbers.
    I would now like to create a range of random numbers within one of these worksheets. I believe I should be using the Randomize and RND methods contained within the VBA OLE object. This is what I've done so far :
    DATA: gs_vba TYPE ole2_object,           "VBA object
               gs_math TYPE ole2_object.
    CREATE OBJECT gs_vba 'VBA'.
    CALL METHOD OF gs_vba 'MATH' = gs_math.
    CALL METHOD OF gs_math 'Randomize' = gs_math.
    CALL METHOD OF gs_math 'Rnd' = gs_math
      EXPORTING
        #1 = 1000.
    Is the above the right way to do it? If not, I would really appreciate your help, and if possible, some sample code to do this as well.
    Thanks and regards,
    Adeline.

    Hi,
    I've managed to create an excel spreadsheet by creating an object of type EXCEL.APPLICATION. I've also managed to rename the worksheet tabs, move from one tab to another as well as fill certain cells with numbers.
    I would now like to create a range of random numbers within one of these worksheets. I believe I should be using the Randomize and RND methods contained within the VBA OLE object. This is what I've done so far :
    DATA: gs_vba TYPE ole2_object,           "VBA object
               gs_math TYPE ole2_object.
    CREATE OBJECT gs_vba 'VBA'.
    CALL METHOD OF gs_vba 'MATH' = gs_math.
    CALL METHOD OF gs_math 'Randomize' = gs_math.
    CALL METHOD OF gs_math 'Rnd' = gs_math
      EXPORTING
        #1 = 1000.
    Is the above the right way to do it? If not, I would really appreciate your help, and if possible, some sample code to do this as well.
    Thanks and regards,
    Adeline.

  • Creating random numbers

    how do you create random numbers between a given set of integers?
    for example, how would you create random numbers from 2 to 9?

    public class Test {
        public static void main (String[] parameters) {
            for (int i = 0; i < 100; i ++) {
                if (i > 0) {
                    System.out.print (", ");
                    if (i % 10 == 0) {
                        System.out.println ();
                System.out.print ((int) (8 * Math.random ()) + 2);
    }code]Kind regards,
      Levi                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Creating x random numbers that add up to a certain number

    How would I go about creating 3 random numbers from x - y that add up to a certain number.
    Or how would i create a set of numbers that are random but not repeating.

    How would I go about creating 3 random numbers fromx
    - y that add up to a certain number.Create 2 random numbers. Number 3 = certain
    number - (random number 1 + random number 2)
    http://java.sun.com/j2se/1.5.0/docs/api/java/util/Rand
    om.html
    Or how would i create a set of numbers that are
    random but not repeating.Create a List and fill it with numbers 1 - n. Shuffle
    the list with the Collections.shuffle(...) method.
    http://java.sun.com/j2se/1.5.0/docs/api/java/util/Coll
    ections.htmlOr use a Set instead of a List, since Sets do not contain duplicates.
    http://java.sun.com/j2se/1.5.0/docs/api/java/util/Set.html
    ? {?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • I need help with this program ( Calculating Pi using random numbers)

    hi
    please understand that I am not trying to ask anymore to do this hw for me. I am new to java and working on the assignment. below is the specification of this program:
    Calculate PI using Random Numbers
    In geometry the ratio of the circumference of a circle to its diameter is known as �. The value of � can be estimated from an infinite series of the form:
    � / 4 = 1 - (1/3) + (1/5) - (1/7) + (1/9) - (1/11) + ...
    There is another novel approach to calculate �. Imagine that you have a dart board that is 2 units square. It inscribes a circle of unit radius. The center of the circle coincides with the center of the square. Now imagine that you throw darts at that dart board randomly. Then the ratio of the number of darts that fall within the circle to the total number of darts thrown is the same as the ratio of the area of the circle to the area of the square dart board. The area of a circle with unit radius is just � square unit. The area of the dart board is 4 square units. The ratio of the area of the circle to the area of the square is � / 4.
    To simuluate the throwing of darts we will use a random number generator. The Math class has a random() method that can be used. This method returns random numbers between 0.0 (inclusive) to 1.0 (exclusive). There is an even better random number generator that is provided the Random class. We will first create a Random object called randomGen. This random number generator needs a seed to get started. We will read the time from the System clock and use that as our seed.
    Random randomGen = new Random ( System.currentTimeMillis() );
    Imagine that the square dart board has a coordinate system attached to it. The upper right corner has coordinates ( 1.0, 1.0) and the lower left corner has coordinates ( -1.0, -1.0 ). It has sides that are 2 units long and its center (as well as the center of the inscribed circle) is at the origin.
    A random point inside the dart board can be specified by its x and y coordinates. These values are generated using the random number generator. There is a method nextDouble() that will return a double between 0.0 (inclusive) and 1.0 (exclusive). But we need random numbers between -1.0 and +1.0. The way we achieve that is:
    double xPos = (randomGen.nextDouble()) * 2 - 1.0;
    double yPos = (randomGen.nextDouble()) * 2 - 1.0;
    To determine if a point is inside the circle its distance from the center of the circle must be less than the radius of the circle. The distance of a point with coordinates ( xPos, yPos ) from the center is Math.sqrt ( xPos * xPos + yPos * yPos ). The radius of the circle is 1 unit.
    The class that you will be writing will be called CalculatePI. It will have the following structure:
    import java.util.*;
    public class CalculatePI
    public static boolean isInside ( double xPos, double yPos )
    public static double computePI ( int numThrows )
    public static void main ( String[] args )
    In your method main() you want to experiment and see if the accuracy of PI increases with the number of throws on the dartboard. You will compare your result with the value given by Math.PI. The quantity Difference in the output is your calculated value of PI minus Math.PI. Use the following number of throws to run your experiment - 100, 1000, 10,000, and 100,000. You will call the method computePI() with these numbers as input parameters. Your output will be of the following form:
    Computation of PI using Random Numbers
    Number of throws = 100, Computed PI = ..., Difference = ...
    Number of throws = 1000, Computed PI = ..., Difference = ...
    Number of throws = 10000, Computed PI = ..., Difference = ...
    Number of throws = 100000, Computed PI = ..., Difference = ...
    * Difference = Computed PI - Math.PI
    In the method computePI() you will simulate the throw of a dart by generating random numbers for the x and y coordinates. You will call the method isInside() to determine if the point is inside the circle or not. This you will do as many times as specified by the number of throws. You will keep a count of the number of times a dart landed inside the circle. That figure divided by the total number of throws is the ratio � / 4. The method computePI() will return the computed value of PI.
    and below is what i have so far:
    import java.util.*;
    public class CalculatePI
      public static boolean isInside ( double xPos, double yPos )
         double distance = Math.sqrt( xPos * xPos + yPos * yPos );        
      public static double computePI ( int numThrows )
        Random randomGen = new Random ( System.currentTimeMillis() );
        double xPos = (randomGen.nextDouble()) * 2 - 1.0;
        double yPos = (randomGen.nextDouble()) * 2 - 1.0;
        int hits = 0;
        int darts = 0;
        int i = 0;
        int areaSquare = 4 ;
        while (i <= numThrows)
            if (distance< 1)
                hits = hits + 1;
            if (distance <= areaSquare)
                darts = darts + 1;
            double PI = 4 * ( hits / darts );       
            i = i+1;
      public static void main ( String[] args )
        Scanner sc = new Scanner (System.in);
        System.out.print ("Enter number of throws:");
        int numThrows = sc.nextInt();
        double Difference = PI - Math.PI;
        System.out.println ("Number of throws = " + numThrows + ", Computed PI = " + PI + ", Difference = " + difference );       
    }when I tried to compile it says "cannot find variable 'distance' " in the while loop. but i thought i already declare that variable in the above method. Please give me some ideas to solve this problem and please check my program to see if there is any other mistakes.
    Thanks a lot.

    You've declared a local variable, distance, in the method isInside(). The scope of this variable is limited to the method in which it is declared. There is no declaration for distance in computePI() and that is why the compiler gives you an error.
    I won't check your entire program but I did notice that isInside() is declared to be a boolean method but doesn't return anything, let alone a boolean value. In fact, it doesn't even compute a boolean value.

  • Problem with Purchase Order creation with Random numbers .

    Hi Experts
    Currently i am facing an issue with Bapi BAPI_PO_CREATE1 to create Purchase order with random numbers for example items 1, 3,5.
    Please let me know the settings .
    Thanks in Advance

    Hi Neha,
    A reset of the release strategy only takes place if
    -  the changeability of the release indicator is set to '4' in
       case of a purchase requisition and '4' or '6' in case of
       another purchasing document (purchase order, request for
       quotation, contract, scheduling agreement),
    -  the document is still subject to the previous release
       strategy,
    -  the new TOTAL NET ORDER VALUE is higher than the old one.
    The total net order value is linked to CEKKO-GNETW for a purchase order,
    CEBAN-GSWRT for a purchase requisition item-wise release and CEBAN-GFWRT
    for a purchase requisition overall release.
    If you have maintained a Tolerance for value changes during release
    (V_161S-TLFAE), the release strategy is reset when the value of the
    document is higher than the percentage you have specified and if the
    document is still subject to the previous release strategy.
    Review the SAP note 365604 and 493900 for more
    information about Release strategy.
    Regards,
    Ashwini.

  • Random numbers in a table

    I'm new to java, so please bear with me. What I want to do is create a program which chooses random numbers (between 0-9) in a table, and then presents a diagram of how many of each number comes up.
    e.g. if the table size was 10, the output could be something like:
    0 *
    1 **
    2
    3 *
    9 **
    with the stars representing the number of times the number showed up. Any assistance you could provide would be great and appreciated. Thank you

    1) Create a Map. The key will be one of the random numbers, the value will be a counter of the number of times the number has been stored.
    2) Generate a random number.
    3) Place the random number in the map key, and increment the value.
    4)Print the random numbers and as many asterisks as the counter values.
    I believe this is classwork? Asking about problems in the code that are not working is ok - asking people to write sample code for you is not ok. Part of the assignment requires you to read the documentation and figure out how to write the code.

  • Help in generating the same random numbers at every time of executuion

    dear friends
    i am facing a problem that the random numbers generated at time of each exectuion of the program are not the same, i want to generate the same random numbers every time time i run the program. i need your help. i am giving the code in c++ if anybody can help in providing the solution so that i get the same random numbers at every run of the program. waiting for your help
    wit regards
    jaya shankar
    #include<iostream.h>
    #include<stdio.h>
    #include<stdlib.h>
    #include<time.h>
    #include<math.h>
    class density
    int s[150][150],parent[150][150],i,j,l,n,loop;
    public:
    void bd(void);
    void css(void);
    void density :: bd(void)
    cout<<"ENTER THE POPULATION SIZE = ";
    cin>>n;
    cout<<"\nENTER THE NO.OF LOOPS = ";
    cin>>loop;
    for(i=0;i<n;i++)
    for(j=0;j<80;j++)
    s[j]=rand()%2;
    cout<<"s:"<<s[j];
    void density :: css(void)
    int a,b;
    float c;
    for(i=0;i<n;i=i+2)
    b=rand()%100;
    cout<<"random b="<<b;
    main()
    density d;
    d.bd();
    d.css();

    You have to read the documentation for the java.util.Random class.
    "If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers. In order to guarantee this property, particular algorithms are specified for the class Random"
    Here is a peace of code that will do wat you need:
    Random rand = new Random(100);
    for(int i=0; i<10; i++)
         System.out.println("Random="+ rand.nextInt(10));

  • Random Numbers with Objective-C

    Hey Guys,
    I'm creating a blackjack program and I need to randomize 52 numbers, ensuring not to repeat any number.
    I know I can use the following to generate a number between 1-52, but I need the to eliminate the possibility of the same card being drawn twice:
    cardNumber = arc4random() % 52 + 1;
    Any idea on how I would do this? Code example would be helpful!
    Thanks,
    Justin

    Hi Justin -
    Justin Carman wrote:
    I'm creating a blackjack program and I need to randomize 52 numbers, ensuring not to repeat any number.
    I would initialize an array (the deck) with the card values, then use your random number as the index into the array. Each time a card is chosen just remove its value from the deck and decrement the modulus of the random numbers. NSMutableArray makes a nice deck for this purpose since its count is automatically decremented each time a value is removed. E.g.:
    // AppController.m
    #import "AppController.h"
    #define N_DECK 52
    @implementation AppController
    @synthesize cardArray; // @property (nonatomic, retain) NSMutableArray *cardArray;
    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    self.cardArray = [NSMutableArray arrayWithCapacity:N_DECK];
    - (IBAction)newDeck:(id)sender {
    [cardArray removeAllObjects];
    for (int i = 0; i < N_DECK; i++) {
    [cardArray addObject:[NSNumber numberWithInt:i+1]];
    // NSLog(@"newDeck: cardArray=%@", cardArray);
    - (IBAction)getCard:(id)sender {
    // check the array
    int count = [cardArray count];
    assert(count <= N_DECK);
    if (count < 1) {
    NSLog(@"getCard: Empty deck");
    return;
    NSLog(@"getCard: count=%d", count);
    // select a card from the array
    int index = arc4random() % count;
    NSNumber *selected = [cardArray objectAtIndex:index];
    NSLog(@"getCard: index=%d selected=%@", index, selected);
    // print the value of the selected card
    int card = [selected intValue];
    NSLog(@"getCard: card=%d", card);
    // remove the selected card from the array
    [cardArray removeObjectAtIndex:index];
    // note selected NSNumber object has been released
    // NSLog(@"getCard: cardArray=%@", cardArray);
    @end
    For extra credit you might want to wrap the above in a custom Deck class.
    Hope that helps!
    - Ray

  • Working with random numbers

    is there a way of creating a series of 6 random numbers from 1-9 without repeating a single number? i have currently developed the following method which so far generates a random number excluding zero, but ive no idea of how to ensure that i get different numbers everytime....
    private int randomNumber ()     {
            int num;
            do {
                   num = (int) (Math.random()*10);
            } while (num == 0);
            return num;
    }anyone got any ideas?

    use this insteadRandom rand = new Random();
        // Random integers that range from from 0 to n
        int n = 10;
       int  i = rand.nextInt(n+1);

  • How do I generate an array of random numbers that relate to an output wave that falls within a certain frequency range?

    I have been creating random numbers that I'm using within a system, the system is working fine, but now I have realised that the random numbers must be outputted to speakers in such a way as to filter out all but a low frequency range.
    I was thinking about generating a dither signal with a bandpass filter, but could not get it to give me out a full array of 250 values which I could then manipulate.
    The sampling frequency of the output is 200Hz and the 250 data points must fall within the 0-100Hz range.
    Another course of action I am considering is to use an FFT and an inverse FFT to get the data that I'm looking for, but I'm fair
    ly inexperienced with using labVIEW and can't quite get it to work.
    Thanks for the help,
    Hank.

    As you may already know, in the Functions palette/Analysis VIs/Filters VIs are VIs for filtering. There are also some examples for using these filters under Examples/Analysis/fltrxmpl. You may find some of these are related to your situation, especially for filtering out the higher values.
    An option is to simply output the random values to a Comparison/"less than or equal" function, where only values <= to 100 would be sent to an array which is in a For loop. Use the iteration counter of the For loop to count up to 250, at which time you would pass the whole array to your next node. This would let you have 250 values between 0 and 100 for your final array.
    Good luck.

  • Array of unique random numbers - help?

    basically, i'm trying to create a BINGO card.
    i stared learning Java a week ago and am finding it easy to learn and use....at least so far.
    my instructor gave me the assignment to created a BINGO card. so i used the system.out.format command to make 5 tab fields, 8 spaces each ("%8s %8s %8s %8s %8s", "B", "I", "N", "G", "O"). although the assignment only wanted me to think numbers out of thin air, just to use as examples, i went above and beyond with the idea to make a BINGO card generator that could actually function.
    then i started the random number sequences, using the Math.random() command. all told, there are 24 of these in the program, one for each number on a bingo card. the field in the middle is the FREE space, so it has no Math.random command.
    in BINGO, each letter (one of my five tab fields) can have a number in ranges of 15. B is 1 to 15, I is 16 to 30, etc. it looks similar to this:
    B I N G O
    9 19 39 57 66
    3 28 32 51 74
    3 29 FREE 46 70
    14 28 43 55 67
    9 24 35 59 62
    as you can tell, i'm having trouble with actually making unique random numbers so that none repeat.
    is there a command or string or something to help me accomplish this?

    The best way I've come up with is to use an object to store the numbers that implements Collection--like ArrayList...
    Then you load it with the range of numbers that you want and call, shuffle() on the object, that will randomize your range of numbers and then you can choose the quantity you want from the storage object. So let's say you need 25 number in the range of 1 to 100:
    Add the numbers (you have to use classes so I would do Integers) 1 to 100;
    call shuffle()
    pull back the first 25 numbers
    This will guarantee that each number is distinct and in a random order.
    If you need multiple sheets populated, you can just call shuffle() between population of each sheet.
    package Junk;
    import java.util.ArrayList;
    import java.util.Collections;
    class Junk{
      private ArrayList<Integer> l;
      Junk(){
        l = new ArrayList<Integer>();
      public void loadList(int s, int e){
        for(int i=s; i<=e; i++){
          l.add(new Integer(i));
      public void randomizeList(){
        Collections.shuffle(l);
      public void printList5(){
        for(int i=0; i<5; i++){
          System.out.println(l.get(i));
      public static void main(String[] args){
        Junk j = new Junk();
        j.loadList(10,99);
        j.randomizeList();
        j.printList5();
        System.out.println();
        j.randomizeList();
        j.printList5();
    }

  • Random numbers, whithin a button handler class

    For my last project I need to create a program that opens a window with 10 text boxes, all displaying "0" at first and a button labled New Numbers. When this button is pushed it needs to generate random numbers within all of the text fields. I have been able to create one that has the text boxes and the button, but in the button handler class the random numbers will not generate properly.I figured that if I could get the button handler class to at least change just the first text field then I would be able to get the rest, but I can't even seem to get that far. Below is what I have so far, any help or guidence would really be appreciated.. Thanks
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Program6
         public static void main(String [] args)
              MyFrame frame = new MyFrame("Alan Jackson - Program 6");
              frame.pack();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setVisible(true);
    class MyFrame extends JFrame
         JTextField [] txt = new JTextField[10];
         JButton btnNewNumbers;
         public MyFrame(String S)
              super(S);
              setLayout(new FlowLayout());
              btnNewNumbers = new JButton("New Numbers");
              int i = 0;
              while(i<10)
                   txt[i] = new JTextField("0",12);
                   add(txt);
                   i++;
              add (btnNewNumbers);     
              btnNewNumbers.addActionListener(new ButtonHandler());
              class ButtonHandler implements ActionListener
                   public void actionPerformed(ActionEvent random)
                        txt[0].setText((int) (Math.random() * 100 +1));                    

    Next time, please use CODE tags, to post your code.
    class MyFrame extends JFrame{
         JTextField [] txt = new JTextField[10];
         JButton btnNewNumbers;
         public MyFrame(String S){
              super(S);
              setLayout(new FlowLayout());
              btnNewNumbers = new JButton("New Numbers");
              int i=0;
              while(i<10){
                   txt[i] = new JTextField("0",12); //<<<<< changed
                   add(txt);
                   i++;
              add (btnNewNumbers);
              btnNewNumbers.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent random){
                        for(int i = 0; i< 10; i++){
                             txt[i].setText(Integer.toString((int) (Math.random() * 100 +1)));

  • Random numbers to make simple bingo game

    Hi folks.
    I am making a simple Bingo game in Director.
    1. generate a random number up to 75; Number=random(75)
    2. check if this number is on a list
    3. if not the number is valid and code executed to display
    the "bingo ball"
    4. add the number to the list
    and repeat.
    Is this valid? Are there problems with this approach, ie. as
    the numbers are called, the random number generated has more
    likelihood of being on the list already so will speed take a hit?
    OR is there another way to do this?
    Thanks in advance

    The issue with your approach will be evident when you've
    removed a bunch of numbers already. What you will see is that the
    number of times you will have to repeat step 2 will grow each time
    you draw a bing ball as the number of balls drawn increases. How I
    would approach it is in the reverse...
    1. create your list of numbers from 1 to 75, procedurally at
    the beginning:
    bingoList = []
    repeat witih j = 1 to 75
    bingoList.add(j)
    end repeat
    -- that gives us a list containing the numbers from 1 to 75.
    2. Now, all you have to do is generate a random number based
    off the number of items in the list and then remove that item from
    the list:
    listCount = bingoList.count
    bingoBallPosition = random(listCount)
    -- get the bingo ball value at the position in the list:
    bingoBall = bingoList[bingoBallPosition]
    -- remove that ball number from the list
    bingoList.deleteAt(bingoBallPosition)
    You will have to do other things such as setting the
    bingoList as a global or property variable depending on how you
    code your project....
    you may want to se this up in a moviescript if you're a
    novice programmer so you can call the handlers from anywhere in
    your project... so you'd probably want to create a newGame handler
    that would set up your list (and other stuff)....
    -- moviescript
    global bingoList, bingoBall
    on newGame
    bingoList = []
    repeat witih j = 1 to 75
    bingoList.add(j)
    end repeat
    end newGame
    on getBingoBall
    listCount = bingoList.count
    bingoBallPosition = random(listCount)
    -- get the bingo ball value at the position in the list:
    bingoBall = bingoList[bingoBallPosition]
    -- remove that ball number from the list
    bingoList.deleteAt(bingoBall)
    -- do other stuff here such as display the bingo ball
    end getBingoBall

Maybe you are looking for