Wednesday 2 August 2017

Java Code to generate the pseudo-random numbers

Problem:

Use the linear congruential method to generate a uniform set of pseudo-random numbers.
x(n+1) = (axn + b) mod m

Solution:

package com.myprograms;

import java.util.ArrayList;
import java.util.List;

public class PseudoRandomNumberGeneration {

List<Integer> randomNumbers = new ArrayList<Integer>();
int x = 5;
int a = 137;
int b = 1;
int m = 256;
int how_many = 256;

public static void main(String[] args) {
PseudoRandomNumberGeneration pseudoRandomNumberGeneration = new PseudoRandomNumberGeneration();
pseudoRandomNumberGeneration.generateRandomNumbers();
pseudoRandomNumberGeneration.printTheResult();

}

public void generateRandomNumbers(){
for (int i = 0; i < how_many; i++) {
x = ((a * x) + b)%m;
randomNumbers.add(x);
}
}

public void printTheResult(){
System.out.println("the random numbers are " + randomNumbers);
}

}


Output:

the random numbers are [174, 31, 152, 89, 162, 179, 204, 45, 22, 199, 128, 129, 10, 91, 180, 85, 126, 111, 104, 169, 114, 3, 156, 125, 230, 23, 80, 209, 218, 171, 132, 165, 78, 191, 56, 249, 66, 83, 108, 205, 182, 103, 32, 33, 170, 251, 84, 245, 30, 15, 8, 73, 18, 163, 60, 29, 134, 183, 240, 113, 122, 75, 36, 69, 238, 95, 216, 153, 226, 243, 12, 109, 86, 7, 192, 193, 74, 155, 244, 149, 190, 175, 168, 233, 178, 67, 220, 189, 38, 87, 144, 17, 26, 235, 196, 229, 142, 255, 120, 57, 130, 147, 172, 13, 246, 167, 96, 97, 234, 59, 148, 53, 94, 79, 72, 137, 82, 227, 124, 93, 198, 247, 48, 177, 186, 139, 100, 133, 46, 159, 24, 217, 34, 51, 76, 173, 150, 71, 0, 1, 138, 219, 52, 213, 254, 239, 232, 41, 242, 131, 28, 253, 102, 151, 208, 81, 90, 43, 4, 37, 206, 63, 184, 121, 194, 211, 236, 77, 54, 231, 160, 161, 42, 123, 212, 117, 158, 143, 136, 201, 146, 35, 188, 157, 6, 55, 112, 241, 250, 203, 164, 197, 110, 223, 88, 25, 98, 115, 140, 237, 214, 135, 64, 65, 202, 27, 116, 21, 62, 47, 40, 105, 50, 195, 92, 61, 166, 215, 16, 145, 154, 107, 68, 101, 14, 127, 248, 185, 2, 19, 44, 141, 118, 39, 224, 225, 106, 187, 20, 181, 222, 207, 200, 9, 210, 99, 252, 221, 70, 119, 176, 49, 58, 11, 228, 5]

No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...