I want to generate a random point(x,y) in java which should lie within a 2D plane {(1,1)(1,-1)(-1,1)(-1,-1)} where both positive & negative X & Y axis is considered.Thank you
Asked
Active
Viewed 1.0k times
-6
-
You create two random floating point values between 0 and 1; and then you randomly multiply with -1. All of that is really basic stuff that you can look up within minutes using your favorite search engine – GhostCat Mar 23 '17 at 10:10
-
How about use new Random().nextFloat()? – Wietlol Mar 23 '17 at 10:10
-
Also, please specify what you mean by "random". Which probability mass function should be used? – Turing85 Mar 23 '17 at 10:16
-
thank you @ Wietlol – Shreyas Shetty Mar 23 '17 at 10:33
3 Answers
2
Take a look at article https://www.tutorialspoint.com/java/util/java_util_random.htm. All you need to do is to generate pairs of floats in range (-1,1). You should use method nextFloat() from class Random. It will give you numbers in range (0,1). Then multiply it by 2 and subtract 1 and you will have numbers in desired interval.

Marcin Tarka
- 56
- 4
-1
Use this method below to return you the random points
public String randXYPoint(){
//For x and y, the maximum point is 1 and Minimum point is -1
//maximum number
int min = -1;
//minimum number
int max = 1;
// generates x values
double xValue = min + Math.random() * (max - min);
// generates y values
double yValue = min + Math.random() * (max - min);
//returns and converts points to string
return String.valueOf(xValue)+ ", "+ String.valueOf(yValue);
}
Just call the method
System.out.println(randrandXYPoint())

Jjingo
- 1
- 1
- 4