-3

I don't have access to a compiler atm, but I was thinking about how I would generate a random float value. To generate a random integer value, I would use:

Random r = new Random();
int x = r.nextInt(8) + 9;

How would I generate a randon number between, lets say, 6.2 and 7.4?

Autar
  • 1,589
  • 2
  • 25
  • 36
dazbrad
  • 182
  • 1
  • 12
  • 1
    6.2 is not an integer. – Suresh Atta Jun 11 '14 at 13:47
  • 10
    Generate a random number between 62 and 74 and divide by 10? – devnull Jun 11 '14 at 13:47
  • 3
    Generate a double between 0 and 1 (see the Random docs), multiply by 1.2 and add 6.2... – Jon Skeet Jun 11 '14 at 13:48
  • 1
    You should be capable to adapt [Generating random integers in a range with Java](http://stackoverflow.com/questions/363681/generating-random-integers-in-a-range-with-java) to `float` or `double` type. – Oleg Estekhin Jun 11 '14 at 13:48
  • Truly random floating point number is kind of hard since it's not a discrete group. Still, you can do between 62 and 74 div by 10 for one decimal point, 620 and 740 div by 100 for two decimal points and so forth... – Janis F Jun 11 '14 at 13:50
  • See [this](http://stackoverflow.com/questions/3680637/how-to-generate-a-random-double-in-a-given-range) old question. It may help. – Nathan Jun 11 '14 at 13:50
  • +1 to Jon Skeet. To make his solution clearer, 1.2 is not a magic number. It's the result of `7.4 - 6.2`. – JB Nizet Jun 11 '14 at 13:51
  • 6.2 is not an integer?!? Thanks devnull, theres a good method. I was thinking it might be like Oleg is suggesting. Thanks anyhow. – dazbrad Jun 11 '14 at 13:54

3 Answers3

5

I would do something like this:

float min = 6.2f;
float max = 7.4f;
float result = (float)Math.random() * (max - min) + min;

Reference Math.random()

Btw. here is a online Compiler for Java: CompileOnline.com

Denuath
  • 130
  • 1
  • 6
2

As devnull says, simply a random number between 62 and 74 and divide by 10.

Here's an example:

Random r = new Random();
double d = (double) ((r.nextInt(75) + 62) / 10d);
System.out.println(d);
Community
  • 1
  • 1
Mena
  • 47,782
  • 11
  • 87
  • 106
2

Ok find the difference of x and y and store it in a double value. Then to get the value you simply multiply the difference(stored double value) by Math.random() (and store it somewhere possibly), which gives a value from 0 to 1; excluding one. Then add the smaller of the value of the random difference here. It can possibly be your minimum value or very very close to your higher value. Dont bother with ints this will give you more authentic random results.