GIS_DBA
GIS_DBA

Reputation: 221

How to generate random numbers the give fixed results using Math.random

I am new in JAVA and I think I have searched all the questions without finding one similar to my question.

I want to generate random numbers that would give back 4 fixed numbers using Math.random(). The numbers that I want to get are: 0, 90. 180 and 270. In other words, I want to 4 numbers with a minimum value of 0 and maximum value of 270 and an increment of 90.

Upvotes: 3

Views: 4034

Answers (2)

leonbloy
leonbloy

Reputation: 75896

You'd better create a java.util.Random object and reuse it:

   Random r = new java.util.Random();
   ...
   int x = r.nextInt(4)*90;

Upvotes: 0

Flight Odyssey
Flight Odyssey

Reputation: 2287

int rand = ((int)(Math.random()*4)) * 90;

Let's break that down. Start with Math.random(), returning a random decimal in the range [0,1). (Anything between 0 and 0.999999999..., loosely.)

Math.random()*4 //Gives a random decimal between 0 and 4 (excluding 4)

Next, let's truncate the decimal.

(int)(Math.random()*4) //Truncates the decimal, resulting in a random int: 0, 1, 2, or 3

Finally, we'll multiiply by 90.

int rand = ((int)(Math.random()*4)) * 90; //0*90=0, 1*90=90, 2*90=180, or 3*90=270

Upvotes: 11

Related Questions