Clarke Woogner
Clarke Woogner

Reputation: 113

Generate Random X.XXX numbers between [-2, 2]

x = rd.nextInt((4000) - 2000) / 1000.0;

This is generating numbers between [0, 2] to the thousandth decimal which is what I want, I just also need negative number so the range of numbers generated is between [-2, 2].

Upvotes: 7

Views: 1132

Answers (4)

Bohemian
Bohemian

Reputation: 424983

The problem you are facing is integer arithmetic, which truncates the fractional part of the result. Use rd.nextDouble() instead so the arithmetic results are double, which retains the fractional part.

However, to round to 1/100ths, you can use integer arthmetic to your advantage.

Your question has the text to the hundredth decimal, so here's that solution:

x = (int)(((rd.nextDouble() * 4) - 2) * 100) / 100d;

But your title mentions X.XXX, so here's that solution:

x = (int)(((rd.nextDouble() * 4) - 2) * 1000) / 1000d;

To unravel what's going on here:

  1. generate random double between 0.000000 and 1.000000
  2. multiply by the scale of the range, so we get a number between 0.000000 and 4.000000
  3. subtract 2, so we get a number between -2.000000 and 2.000000
  4. multiply by 1000, so we get a number between -2000.000000 and 2000.000000
  5. cast to int to truncate the fraction, so we get a int between -2000 and 2000
  6. divide by 1000d (which is a double), so we get a double between -2.000 and 2.000

Upvotes: 5

Luka Kralj
Luka Kralj

Reputation: 446

You can generate random number on a range [0,4] and then simply subtract 2 from the result:

x = (rd.nextInt(4000) / 1000.0) - 2;

Upvotes: -1

Rotartsi
Rotartsi

Reputation: 567

You can generate a random float and then use a modulo to truncate it to the hundredth decimal place.

int min = -2;
int max = 2;
Random rand = new Random();
float ret = rand.nextFloat() * (max - min) + min;
return ret - (ret % 0.01);

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201429

Floating point numbers do not always have a precise number of digits. Also, the third decimal place is called thousandths (the hundredth decimal would be the second digit after the .). I think you know this because you are dividing by a thousand. So, step one: generate a single random value between 0 and 4 as a double. Step two: Subtract two and convert to a formatted String (so you can control the number of digits).

double d = (rd.nextDouble() * 4) - 2;
String x = String.format("%.3f", d);

Upvotes: 2

Related Questions