-6

Can anyone please suggest me a random number algorithm that I can use for implementation in java? I don't want to use the Math.random() function.

Note: I want to write my own random number generation function in java; therefore for I am looking for an algorithm that I can use.

akhouri
  • 3,065
  • 3
  • 25
  • 29
  • Are you looking for [Random](http://docs.oracle.com/javase/7/docs/api/java/util/Random.html) ? – donfuxx May 05 '14 at 00:21
  • 1
    [Generating random numbers in a range with Java](http://stackoverflow.com/q/363681) – Bernhard Barker May 05 '14 at 00:22
  • 3
    *Why* don't you want to use `Math.random()`? – kdgregory May 05 '14 at 00:26
  • You will need to seed system time... [System.currentTimeMillis()](http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#currentTimeMillis()) – Mr. Polywhirl May 05 '14 at 00:34
  • 1
    Check out this question for more suggestions: [SO: How to generate a random number from scratch](http://stackoverflow.com/questions/1967491/how-to-generate-a-random-number-from-scratch) – Mr. Polywhirl May 05 '14 at 00:39
  • @kdgregory I want to write my own random number generation function in java; therefore for I am looking for an algorithm that I can use. – akhouri May 05 '14 at 00:46
  • What are your requirements? Sheesh. – Maarten Bodewes May 05 '14 at 01:00
  • That does not answer kdgregory's question... – Kevin Krumwiede May 05 '14 at 01:50
  • @vas - I asked because the reason will determine what sort of answer is appropriate. For example: you need crytographically-secure randomness. If you just want to reinvent the wheel, then Google turns up lots (2MM+) of results. And since you have no real requirements, you could have picked one arbitrarily. – kdgregory May 05 '14 at 11:33
  • @kdgregory thanks for your suggestions; i will try google search for some algos for my research. – akhouri May 06 '14 at 00:37

1 Answers1

2

I think your question actually language-agnostic, and shouldn't be specifically java. Also, I think it's very easy to find information on things like this. Look at the wiki pages for Pseudorandom number generator and Random number generation. If you're looking for something simple (relatively) look at the XORshift RNG

uint32_t xor128(void) { //A C version from wiki
  static uint32_t x = 123456789;
  static uint32_t y = 362436069;
  static uint32_t z = 521288629;
  static uint32_t w = 88675123;
  uint32_t t;

  t = x ^ (x << 11);
  x = y; y = z; z = w;
  return w = w ^ (w >> 19) ^ (t ^ (t >> 8));
}

Or in Java:

public class IsNotFour {
    int x = 123456789;
    int y = 362436069;
    int z = 521288629;
    int w = 88675123;

    int xor128() { // A converted C version from wiki
        int t = x ^ (x << 11);
        x = y;
        y = z;
        z = w;
        w = w ^ (w >>> 19) ^ (t ^ (t >>> 8));
        return w; 
    }
}

Note that x, y, z and w together make the seed.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
Kyranstar
  • 1,650
  • 2
  • 14
  • 35