Reputation: 2339
I am trying to figure out a way to generate random values between 1/2 and -1/2.
I tried something as below, but not sure if this is a right way to do it....
Can someone please let me know a good way to implement this?
public static void main(String args[]) {
double Max = .5;
double Min = -0.5;
for (int i = 0; i < 10000; i++) {
double value = Min + ((Math.random()) * (Max - Min));
System.out.println(value);
}
}
Upvotes: 3
Views: 913
Reputation: 129587
Well Math.random()
returns a random double between 0
and 1
, so to change the range to -1/2
to 1/2
, we can just subtract 1/2
(since 0 - 1/2 = -1/2
and 1 - 1/2 = 1/2
):
Math.random() - 0.5
What you are doing now is more general, i.e. if you want a double between min
and max
the appropriate expression would be
min + Math.random() * (max - min)
In this case, plugging in min = -0.5
and max = 0.5
we have
-0.5 + Math.random() * (0.5 - -0.5)
which simplifies to
Math.random() - 0.5
I should also mention that, if you read the random()
method's documentation, you will find that it returns a double greater than or equal to 0.0 and less than 1.0. This means that the expression above should produce a number in the range [-0.5, 0.5)
, meaning that -0.5
can potentially be returned but 0.5
cannot be.
Upvotes: 9
Reputation: 89
Bear in mind that the Math.Random() class is going to return a value between 0 and 1, not including 1.
In this case, Math.Random()-0.5
will work sweetly
Upvotes: 1
Reputation: 59363
You could just do:
Math.random() - 0.5
This is because the min of Math.random()
is 0, and the max is 1. If you subtract a half, the min will be 0 - 0.5 == -0.5
and the max will be 1 - 0.5 == 0.5
.
Therefore, your original code can be shortened to:
public static void main(String args[]) {
for (int i = 0; i < 10000; i++) {
double value = Math.random() - 0.5; // no need for a "double" cast,
// Math.random() returns a double
System.out.println(value);
}
}
Upvotes: 5