0

I am trying to make a random point on a coordinate plane, and I want the x and y to be two random floating point numbers between -2.0 and 2.0

Given that I have tried

x  = (random.nextDouble() - 2);
y  = (random.nextDouble() - 2);

The above will only return (x,y) in the negative quadrant of the coordinate plane.

How do I make it so that it will reach all four quadrants equally?

Bohemian
  • 412,405
  • 93
  • 575
  • 722
user3277633
  • 1,891
  • 6
  • 28
  • 48
  • You state in the title, that you want a random float, now you are working with doubles. How are x and y defined? If they are floats, than this is part of the problem. Please post the whole code. – Turing85 Nov 05 '14 at 21:41
  • @Turing85 double is a floating point type, so the use of "float" is reasonable and clear – Bohemian Nov 05 '14 at 21:43
  • @Bohemian not, if x and y are defined as floats. – Turing85 Nov 05 '14 at 21:46
  • @Turing85 They aren't floats; if they were the code wouldn't compile. – Bohemian Nov 05 '14 at 21:50
  • possible duplicate of [Generating random integers in a range with Java](http://stackoverflow.com/questions/363681/generating-random-integers-in-a-range-with-java) – DavidPostill Nov 05 '14 at 21:52

5 Answers5

3

Create a number in the range 0-4 (the same magnitude or your target range) then subtract 2 to align the start/end of the range:

x = random.nextDouble() * 4 - 2;

FYI small point: it is not necessary to use double constants, such as 4.0 in the expression, because when one of the operands of an arithmetic operation is double, java will perform an automatic (safe) widening of other types to double.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
1

random.nextDouble() returns a random value between 0.0 and 1.0, so if you just subtract 2, you will get a random value between -2.0 and -1.0.

You also have to scale the value - multiply it by the size of the range, which is 4 in your case:

x = 4.0 * random.nextDouble() - 2.0;
y = 4.0 * random.nextDouble() - 2.0;
Jesper
  • 202,709
  • 46
  • 318
  • 350
0

random.nextDouble() only returns 0.0 to 1.0 you need to multiply it by 4 first

x  = (random.nextDouble() * 4 - 2);
y  = (random.nextDouble() * 4 - 2);
Chris Stillwell
  • 10,266
  • 10
  • 67
  • 77
0

Simple: You only need scale it. Subtract .5 to get a number in the range from -.5 to .5, and then multiply that by 4 and you have between -2 and 2.

x  = ((random.nextDouble() - .5) * 4);
y  = ((random.nextDouble() - .5) * 4);
Pokechu22
  • 4,984
  • 9
  • 37
  • 62
0

So random.nextDouble() returns a number 0-.9999 so you have to times it by your range -2 - 2 = 4

and then subtract 2 in order to get the -2 to 2

x = (random.nextDouble()*4 -2)

y = (random.nextDouble()*4 -2)

iRunner
  • 58
  • 8