som86
som86

Reputation: 61

Random number generator that generates integers for Java

I want to generate some random integers in Java, but this according to some distribution laws. More specific:

Can you help me? Do you know a library which can do what I want? I studied Michael Flanagan's library, colt and apache's Commons Math but they don't have what I need.

Thanks!

Upvotes: 5

Views: 2230

Answers (4)

Giuseppe Cardone
Giuseppe Cardone

Reputation: 5393

I suggest you to use the Uncommons Maths library, which comprises different random generators (e.g. Mersenne Twister, AES-based) and distributions (poisson, gaussian and so on)

As for the "double problem": almost all random generators generate double because they are the most used. If you need integers you'll need to do the rounding yourself (a call to Math.round will be enough). Let's say that you are generating random people heights with centimeter accuracy: if your random generator returns 175.234, you can just round it to 175. That's really not a problem.

As for the limits for exponential distribution: there are no generators that let you choose limits because no such limits exist for exponential distribution. An exponential distribution typically models the delays between two consecutive events in a Poisson process: the delay can be as low as 0, or can be extremely high. The extremely high outcomes are really really unlikely, but they are not impossible. you can solve the problem by getting a random number from the generator, adding your lower limit and using Math.max to trim it if it is higher than your upper limit. But this is no longer an exponential distribution.

Upvotes: 3

Klark
Klark

Reputation: 8300

If you have a double number from 0 to 1 you can scale it to the integer:

int res = lowLimit + (int)(myRandFunction() * (highLimit - lowLimit));

Edit:

Why I got a vote down? He sad he has a function that returns a double in distribution he wants (I guessed a double form 0 to 1), so this is going to do the job.

Upvotes: 2

flownt
flownt

Reputation: 760

boost has some really nice random number generators, i know its c++ and not java, but the implementations should be a good guide to implementing them yourself.

http://www.boost.org/doc/libs/1_43_0/doc/html/boost_random.html

Upvotes: -1

dty
dty

Reputation: 18998

Just generate a double and scale it to the integer range you require. For example, if a regular (uniform) random number generator generates numbers from 0.0 to 1.0 and you want numbers from 0 to 100, you'd just multiply the generated random number by 100.

Upvotes: -1

Related Questions