0

How can i set these values using the Random to a random decimal number that is between 0 and 100?

xPos = Math.round((Math.random() * 100) * 10) / 10;
yPos = Math.round((Math.random() * 100) * 10) / 10;

i am trying to set the values xPos and yPos to random decimals between 0 and 100

kaan mote
  • 29
  • 4
  • Check [Java Generate Random Number Between Two Given Values](http://stackoverflow.com/questions/5271598/java-generate-random-number-between-two-given-values) – sam Nov 06 '15 at 14:52
  • 3
    What is your problem, exactly? Why not just crate an instance of `Random` and use the [`nextInt(int bound)`](https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#nextInt-int-) method? – mkobit Nov 06 '15 at 14:53
  • http://stackoverflow.com/questions/7961788/math-random-explained – jwde Nov 06 '15 at 14:53
  • What do you mean by random decimal number? If you just want a random `double` in the range [0, 100) then you can use `xPos = Math.random() * 100`. – Phylogenesis Nov 06 '15 at 14:57
  • How precise do you want the output to be? One decimal place? – phflack Nov 06 '15 at 15:01
  • What type are `xPos` and `yPos`? – Elliott Frisch Nov 06 '15 at 15:02

2 Answers2

2

Try this:

Random rand = new Random();
double xPos = rand.nextDouble() * 100;
double yPos = rand.nextDouble() * 100;

nextDouble docs

sam
  • 2,033
  • 2
  • 10
  • 13
-1

To generate a random decimal from [0-100) you can use Math.random() as you are already, or you can use a Random object

Do note by [0-100), these bits of code return numbers from 0 up to, but not including, 100


Math.random():

double xPos = Math.random() * 100;
double yPos = Math.random() * 100;

Math.random() with 1 decimal place:

double xPos = Math.floor(Math.random() * 1000) / 10;
double yPos = Math.floor(Math.random() * 1000) / 10;

Random object:

Random r = new Random();
double xPos = r.nextDouble() * 100;
double yPos = r.nextDouble() * 100;

Random object with 1 decimal place:

Random r = new Random();
double xPos = r.nextInt(1000) / 10.0;
double yPos = r.nextInt(1000) / 10.0;

It is considered better practice to use the Random object, even though Math.random() calls its own internal Random object.

Using Random instead of Math.random() does have the benefit of easier concurrency. Without multiple Random objects, multithreading with heavy usage of randomized numbers will slow down to a crawl

phflack
  • 2,729
  • 1
  • 9
  • 21
  • how do you also round the random()? – kaan mote Nov 06 '15 at 15:25
  • @kaanmote What do you need it rounded to? I have included one decimal place answers which you can scale to two or more. Do you need to round to the nearest half? the nearest int? – phflack Nov 06 '15 at 15:32
  • No explanation for the downvote? One does not help others improve without saying how – phflack Nov 06 '15 at 17:03