Tuesday, October 18, 2011

Generating Random Numbers in Java

To generate random numbers in Java, you will need to call the Math.Random() method from the java.lang package (a package which is available by default, so you don't need to import it in your program).

The Math.Random() method generates a floating-point number (a double) who is in the range [0,1), where 0 represents the lower bound and 1 represents the upper bound.
double randomNumber = Math.Random();
If you want to increase the range of random values, you simply need to multiply the result of the method with the value of the upper bound you want. This way, the value produced by the method will be in the range [0,b), where 0 represents the lower bound and b represents the upper bound.
double b = 16.0;
double randomNumber = Math.Random() * b;
//randomNumber will be in the range [0,16).
If you want to increase the lower bound, you will need to add to the result generated by the method the lower bound value of your range  (that will also increase your upper bound value). This way, the value produced by the method will be in the range [a, a+1), where a represents the lower bound and a+1 represents the upper bound.
double a = 3.0;
double randomNumber = Math.Random() + a;
//randomNumber will be in the range [3,4).
If you want to produce values that are in a specific range [a,b],where a represents the lower bound and b represents the upper bound, you will need to multiply the value generated by the method with (b-a) and add a to the final result.
double a = 3.0, b=16.0;
double randomNumber = (Math.Random() *(b-a)) + a;
//randomNumber will be in the range [3,16).
If you want to obtain negative values, you will just need to switch the sign of your bound variables:
double a=3, b=16;
double rand1 = Math.Random() - a;
//rand1 will be in the range [-3, -2)
double rand2 = Math.random * (-b);
//rand2 will be in the range (-16,0];
double rand3 = (Math.Random * (a-b) -a);
//rand3 will be in the range (-16,-3]
If you want to obtain random integers, you simply typecast the result:
double a = 3.0, b=16.0;
int randomNumber = (int) ( (Math.Random() *(b-a)) + a);
//randomNumber will be in the set {3,4,...,15}

No comments:

Post a Comment

Got a question regarding something in the article? Leave me a comment and I will get back at you as soon as I can!

Related Posts Plugin for WordPress, Blogger...
Recommended Post Slide Out For Blogger