Rovester
Rovester

Reputation: 3

Random number with negative min or max and with 0.5 as possible decimal

So basically I need to generate a number between a min and max (could be negative as well) and there should be a possibility the number could end with a decimal 0.5.

So, for example, the numbers could be 5, 6, -8.5, 3.5.

I have this to generate my number (example):

rand.nextInt(20 + 1 + 10) - 10;

Upvotes: 0

Views: 221

Answers (2)

khelwood
khelwood

Reputation: 59113

You could generate an integer with twice the range you want, and then halve it.

Something like this:

int min = -5;
int max = 15;
double r = min + 0.5 * rand.nextInt(2 * (max - min));

If you want max included in the random range, then:

double r = min + 0.5 * rand.nextInt(2 * (max + 1 - min));

Upvotes: 4

Ben
Ben

Reputation: 1695

Math.round((min + (rand.nextDouble() * Math.abs(max - min))) / 0.5) * 0.5;

should do the trick by creating a correct value in range [min, max] (including both min and max as possible values!)

Upvotes: 0

Related Questions