Generating Random Doubles in Java [duplicate] - java

This question already has answers here:
Generate a random double in a range
(7 answers)
Closed 9 years ago.
I'm a Java noob trying to generate a random double between -10 and 10 inclusive. I know with ints I would do the following:
Random r = new Random();
int i = -10 + r.nextInt(21);
However, with doubles, this doesn't work:
Random r = new Random();
double i = -10 + r.nextDouble(21);
Can someone please explain what to do in the case of doubles?

Try this:
Random r = new Random();
double d = -10.0 + r.nextDouble() * 20.0;
Note: it should be 20.0 (not 21.0)

Try to use this for generate values in given range:
Random random = new Random();
double value = min + (max - min) * random.nextDouble();
Or try to use this:
public double doubleRandomInclusive(double max, double min) {
double r = Math.random();
if (r < 0.5) {
return ((1 - Math.random()) * (max - min) + min);
}
return (Math.random() * (max - min) + min);
}

Returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator's sequence.
nextDouble doesn't take a parameter, you just need to multiply it by whatever your range is. Or more generally:
minimum + (maximum - minimum) * r.nextDouble();

There is no nextDouble(int) method in Random. Use this:
double i = -10.0 + r.nextDouble() * 20.0;
API reference

Related

How to generate a random integer using math.random class [duplicate]

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 7 years ago.
I am having trouble with the RandInt() method as it will not return a random integer. The result must be an int ranged 0-9 and must use the math.random class. This is my code below:
public class RandNumGenerator {
public static int RandInt() {
int n = (int) Math.random() * 10;
return n;
}
public static void main(String[] args) {
RandInt();
}
}
You should cast the double to int after multiplying by 10 :
int n = (int) (Math.random() * 10);
Otherwise you'll always get 0 (since Math.random()<1.0 and therefore (int)Math.random() is always 0).
Casting has higher priority than * so code
(int) Math.random() * 10;
is same as
((int) Math.random()) * 10;
and since Math.random() returns values in range [0; 1) (1 - excluded) casting to int
(int) Math.random()
will produce 0 which multiplied by 10 will also return 0.
You may want to use
(int) (Math.random() * 10)
or easier to read and maintain Random#nextInt(max) to generate range [0; max) (max-exclusive)
You need to put brackets around the multiplication
int n = (int) (Math.random() * 10);
what's happening is
int n = ((int) Math.random()) * 10;
as Math.random() is always greater or equal to 0 and less than 1, converting it to an integer will always equal zero. Multiplying it by 10 will do nothing.
You shouldn't really be using Math.random() to generate random integers, as it will generate random floats (i.e, decimal numbers)
You should do something similar to this
Random myRandom = new Random();
int randomInt = myRandom.nextInt(10);

Creating Minimum Value with Random Operator in Java

I need to generate a random number that is between a minimum value and 1 -> [min, 1)
I have been reading over the random class of java, and have found that when generating a random double, the result is a double from 0 to 1.0, however, you cannot limit the bound.
My original thought was to limit the top value of the random function to .7, but this is not possible with the random function.
If anyone could help me here's my code:
public static double random(){
// generate an random number accuracy within range [min, 1)
Random randomNum = new Random();
double accuracy = min + randomNum.nextDouble();
System.out.println("Min " + min);
return accuracy;
}
If for example we take min to be .2 in this case, then the possible results of the function as I understand are .2 to 1.2. How can I make it simply .2 to 1?
Correct me if I'm wrong, but wouldn't this work:
public static double random(int min, int max){
Random randomNum = new Random();
return (max - min) * randomNum.nextDouble() + min;
}
Explanation:
(max - min) returns the difference between max and min.
randomNum.nextDouble() returns a random number between 0 and 1
+ min will add the min value so it's the lowest value
(max - min) * randomNum.nextDouble() returns a random number between 0 and max-min
(max - min) * randomNum.nextDouble() + min returns a random number between min and max
/**
* A double uniformly distributed in the range [min, max).
* #param min finite and inclusive.
* #param max finite, > min, and exclusive.
* #return d such that min <= d && d < max.
*/
public static boolean uniformInRange(double min, double max, Random r) {
assert min < max && !Double.isInfinite(min) && !Double.isInfinite(max);
return min + (r.nextDouble() * (max - min));
}
To use it, just call
uniformInRange(min, 1.0d, randomNum)
What about something like this?
double min = .2;
Random gen = new Random();
double rand = (gen.nextDouble() * 0.8) + min;
Here you are adding the min bound at the end, and multiplying your 0-1 ratio by 0.8, which is the difference between 0.2 and 1.

Java Random double in interval [-1000, 1000]

In java I have:
Random random = new Random();
double randomNum = random.nextDouble();
which creates a random number between 0 and 1. However I want a number between -1000 and 1000, how would I scale this?
Thanks
2 possibilities:
[less dense]: multiple your results by 2000, and subtract 1000
from the result. It won't be as 'dense' as possibility 2.
get a random int in range [-1000,999], and add a random double in
range [0,1].
Note that possibility 2 ensures better randomness and better 'density' of your numbers, at the cost of 2 random calls [which might be expansive, if it is an issue].
Um, maths?
double randomNum = (random.nextDouble()-0.5d) * 2000;
Random random = new Random();
double randomNum = (random.nextDouble() * 2000.0d) - 1000.0d;
Try this algorithm:
Generate a random value in the range 0 to 1.
multiply that value by 2000 (the size of the desired range).
subtract 1000 from the result of step 2 (move the value into the desired range).
This gives you a number on that range
double randomNum = (random.nextDouble() * 2000) -1000;
Here is a general function you could use to linearly rescale a number between zero and one (val01) to a different range (min..max):
public static double rescale(double val01, double min, double max) {
return val01 * (max - min) + min;
}
public static double doubleBetween(double start, double end) {
Random random = new Random();
// We need 64 bits because double have 53 bits precision, so int is too short
// We have now a value between 0 and Long.MAX_VALUE.
long value = -1L;
while (value < 0)
value = Math.abs(random.nextLong()); // Caution, Long.MIN_VALUE returns negative !
// Cast to double
double valueAsDouble = (double) value;
// Scale so that Long.MAX_VALUE is exactly 1 !
double diff = (end-start)/(double) Long.MAX_VALUE;
return start + valueAsDouble*diff;
}
This will give the correct interval including both ends with full double precision. doubles have a special -0.0 value (the negative zero) which will not be given by this routine.
Random random = new Random();
int randomNum = random.nextInt(2000) - 1000;
public static double randomInterval(double minValue,double maxValue){
Random random = new Random();
double r;
do {
r = random.nextDouble();
} while (r < minValue || r >= maxValue);
return r;
}
Example :
double a = randomInterval(-1000,1000) ;

Getting random numbers in Java [duplicate]

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 3 years ago.
I would like to get a random value between 1 to 50 in Java.
How may I do that with the help of Math.random();?
How do I bound the values that Math.random() returns?
The first solution is to use the java.util.Random class:
import java.util.Random;
Random rand = new Random();
// Obtain a number between [0 - 49].
int n = rand.nextInt(50);
// Add 1 to the result to get a number from the required range
// (i.e., [1 - 50]).
n += 1;
Another solution is using Math.random():
double random = Math.random() * 49 + 1;
or
int random = (int)(Math.random() * 50 + 1);
int max = 50;
int min = 1;
1. Using Math.random()
double random = Math.random() * 49 + 1;
or
int random = (int )(Math.random() * 50 + 1);
This will give you value from 1 to 50 in case of int
or 1.0 (inclusive) to 50.0 (exclusive) in case of double
Why?
random() method returns a random
number between 0.0 and 0.9..., you
multiply it by 50, so upper limit
becomes 0.0 to 49.999... when you add 1, it becomes 1.0 to 50.999..., now when you truncate to int, you get 1 to 50. (thanks to #rup in comments). leepoint's awesome write-up on both the approaches.
2. Using Random class in Java.
Random rand = new Random();
int value = rand.nextInt(50);
This will give value from 0 to 49.
For 1 to 50: rand.nextInt((max - min) + 1) + min;
Source of some Java Random awesomeness.

How to generate random positive and negative numbers in Java [duplicate]

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 4 years ago.
I am trying to generate random integers over the range (-32768, 32767) of the primitive data type short. The java Random object only generates positive numbers. How would I go about randomly creating numbers on that interval? Thanks.
You random on (0, 32767+32768) then subtract by 32768
Random random=new Random();
int randomNumber=(random.nextInt(65536)-32768);
public static int generatRandomPositiveNegitiveValue(int max , int min) {
//Random rand = new Random();
int ii = -min + (int) (Math.random() * ((max - (-min)) + 1));
return ii;
}
Generate numbers between 0 and 65535 then just subtract 32768
This is an old question I know but um....
n=n-(n*2)
([my double-compatible primitive type here])(Math.random() * [my max value here] * (Math.random() > 0.5 ? 1 : -1))
example:
// need a random number between -500 and +500
long myRandomLong = (long)(Math.random() * 500 * (Math.random() > 0.5 ? 1 : -1));
(Math.floor((Math.random() * 2)) > 0 ? 1 : -1) * Math.floor((Math.random() * 32767))
In case folks are interested in the double version (note this breaks down if passed MAX_VALUE or MIN_VALUE):
private static final Random generator = new Random();
public static double random(double min, double max) {
return min + (generator.nextDouble() * (max - min));
}

Categories

Resources