Java Random() rounding off - java

I'm using Java's Random to generate random numbers: 1.0, 1.1 - 10
Random random = new Random();
return (double) ((random.nextInt(91) + 10) / 10.0);
When I printed a lot of these numbers (2000), I noticed 1.0 and 10 are significant less printed than all others (repeated 20 times, happened every time). Most likely because 0.95-0.99 and 10.01-10.04 aren't generated.
Now I have read a lot of threads about this, but it still leaves me to the following question:
If these numbers would represent grades for example, you can't get lower than a 1 and higher than a 10 here, would it be legit to extend the range from 0.95 up to 10.04?
Random random = new Random();
return Double.valueOf((1005-95) / 100);

To generate a random value between 1.1 and 10 use the following code:
double min = 1.1d;
double max = 10d;
Random r = new Random();
double value = min + (max - min) * r.nextDouble();
Afterwarsds you can use Math.floor(value) too round your result

This premise
Most likely because 0.95-0.99 and 10.01-10.04 aren't
generated.
is wrong. You generate random ints from 10 inclusive to 100 inclusive. Lower fractions and rounding of values does not play into it. Random nextInt is random in the interval; the end cases is not discriminated against.
I think your method
Random random = new Random();
return (double) ((random.nextInt(91) + 10) / 10.0);
Looks correct. I would suggest measuring the anomaly you are experiencing, maybe it is a human bias from when you are merely looking at the output.
Here is some code that measures the actual random generation of the 91 values. It is before the conversion to double which is not ideal.(but I do not see how dividing by 10 does anything else than map values as 10 -> 1.0, 11 -> 1.1 ... 99 -> 9.9 and 100 -> 10.0. A measure of the final result would of course be more desirable)
Random random = new Random();
int[] measure = new int[101];
for (int i = 0; i < 10000; i++) {
int number = (random.nextInt(91) + 10);
measure[number]++;
}
for (int i = 0; i < 101; i++) {
System.out.println(i + " count: " + measure[i]);
}
Looking at the results from that code the 10 and 100 values seem to come up as often as any other.

Related

Generate random numbers with different probabilities within given ranges

Is there a simple algorithm that will print results of rolling a die such that the probability of getting 1,2,3,4,5 is 1/9 and the probability of getting a 6 is 3/9.
I would like to implement this in Java and intentionally only use Math.random(), if statements, for/ while loops.
As others suggested to make the sum of all events equal to 1, then number 9 will have a probability of 4/9 to be chosen.
Generate a random number between 1 and 9, inclusive on both ends. If the number be 1 to 5, you rolled that number, otherwise, you rolled 6. Note that there are 4 chances in this scheme to roll a 6, and 5 total chances to roll 1 through 5.
Random random = new Random();
int roll = random.nextInt(9) + 1; // create a random number
if (roll > 5) {
System.out.println("You rolled a 6");
}
else {
System.out.println("You rolled a " + roll);
}
To simulate more dice rolls you can add the above logic inside a for loop that runs for as many loops as you want.
Generating values for random variables with a certain distribution usually works like this:
You have a function which generates a random 0 <= q < 1,
You apply the quantile function and you obtain the value of your variable.
In your case you have a discrete random variable. You need an instance of Random:
private static final Random random = new Random();
the values assumed by the variable:
private static final double[] values = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0};
Compute the cumulative distribution function (sum of probabilities of the values up to the specific value) for these values:
private static final double[] cdf = {1.0 / 9, 2.0 / 9, 3.0 / 9, 4.0 / 9, 5.0 / 9, 1.0};
You random generating function will return the last value for which the cdf is not greater than q:
public static double randomValue() {
double q = random.nextDouble();
for (int i = 0; i < values.length; i++) {
if (q > cdf[i]) continue;
return values[i];
}
throw new IllegalStateException();
}
Seems pretty straightforward:
// Pass in an instance of class Random
public static int gen(Random r) {
int i = r.nextInt(9); // uniformly generate 0,...,8 inclusive
if (i < 5) {
return i + 1; // returns 1,...,5 w/ probability 1/9
} else {
return 6; // returns 6 w/ probability 4/9
}
}
Warning, I no longer have a Java compiler on my machine, so I haven't compiled this. However, the algorithm is valid as confirmed in another language.

random number generation in java with multiple of 1000 a number appear

I am looking to get random number in between 1000 to 8192000. The random number should be like 1000 , 2000,3000 to 8192000.
Following is the code that i have tried but did not got any success.
ran.nextInt(8192000 - 1000)%1000;
What should I change in order to get number in term of 1000, 2000, 3000...
The easiest approach would seem to generate a random number between 1 and 8192 and just multiply it by 1000:
Random randomGenerator = new Random();
long randomNumber = (1 + randomGenerator.nextInt(8192)) * 1000L;
If you want 8192000 inclusive try:
Random random = new Random();
for (int i = 0; i < 10; i++) {
System.out.println((random.nextInt(8192) + 1) * 1000);
}
Here you get values: 1000, 2000, ..., 8192000

How to generate random number to express the probability

I don't know how to make it in JAVA.
Sorry everybody. My case is with 51% probability, I have to do something. and, with 49% probability, I don't have to do anything.
I think I need to generate a random number, which will reference, express the probability.
how can I make it suitable to my case in Java? Thank you in advanced!
You can use the Random class. It has methods such as Random.nextInt where you can give it an upper bound and it will give you a random number between 0 (inclusive) and that number (exclusive). There are also other methods like Random.nextBoolean which returns 50% chance of true or false.
You can use Math.random function alternatively. The tutorial is here
Quoting javadoc.
Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range.
If you want to generate integer then you can use nextInt() method like this -
Random randomGenerator = new Random();
for (int i = 1; i <= 10; ++i){
int randomInt = randomGenerator.nextInt(100);
System.out.println("Generated : " + randomInt);
}
If you want double you can use nextDouble() method -
Random randomGenerator = new Random();
for (int i = 1; i <= 10; ++i){
int randomInt = randomGenerator.nextDouble(100);
System.out.println("Generated : " + randomInt);
}
And if you want to generate random between a range then you can do -
int shift=0;
int range=6;
Random ran = new Random();
int x = ran.nextInt(range) + shift;
This code will generate random number (int) upto 6 (from 0 to 5). If you want to generate random number shifting the lower limit then you can change the shif value. For example changing the shift to 2 will give you all random number greater than or equal 2.

How to get a random between 1 - 100 from randDouble in Java?

Okay, I'm still fairly new to Java. We've been given an assisgnment to create a game where you have to guess a random integer that the computer had generated. The problem is that our lecturer is insisting that we use:
double randNumber = Math.random();
And then translate that into an random integer that accepts 1 - 100 inclusive. I'm a bit at a loss. What I have so far is this:
//Create random number 0 - 99
double randNumber = Math.random();
d = randNumber * 100;
//Type cast double to int
int randomInt = (int)d;
However, the random the lingering problem of the random double is that 0 is a possibility while 100 is not. I want to alter that so that 0 is not a possible answer and 100 is. Help?
or
Random r = new Random();
int randomInt = r.nextInt(100) + 1;
You're almost there. Just add 1 to the result:
int randomInt = (int)d + 1;
This will "shift" your range to 1 - 100 instead of 0 - 99.
The ThreadLocalRandom class provides the int nextInt(int origin, int bound) method to get a random integer in a range:
// Returns a random int between 1 (inclusive) & 101 (exclusive)
int randomInt = ThreadLocalRandom.current().nextInt(1, 101)
ThreadLocalRandom is one of several ways to generate random numbers in Java, including the older Math.random() method and java.util.Random class. The advantage of ThreadLocalRandom is that it is specifically designed be used within a single thread, avoiding the additional thread synchronization costs imposed by the other implementations. Therefore, it is usually the best built-in random implementation to use outside of a security-sensitive context.
When applicable, use of ThreadLocalRandom rather than shared Random objects in concurrent programs will typically encounter much less overhead and contention.
Here is a clean and working way to do it, with range checks! Enjoy.
public double randDouble(double bound1, double bound2) {
//make sure bound2> bound1
double min = Math.min(bound1, bound2);
double max = Math.max(bound1, bound2);
//math.random gives random number from 0 to 1
return min + (Math.random() * (max - min));
}
//Later just call:
randDouble(1,100)
//example result:
//56.736451234
I will write
int number = 1 + (int) (Math.random() * 100);
double random = Math.random();
double x = random*100;
int y = (int)x + 1; //Add 1 to change the range to 1 - 100 instead of 0 - 99
System.out.println("Random Number :");
System.out.println(y);

Generate a random double in a range

I have two doubles like the following
double min = 100;
double max = 101;
and with a random generator, I need to create a double value between the range of min and max.
Random r = new Random();
r.nextDouble();
but there is nothing here where we can specify the range.
To generate a random value between rangeMin and rangeMax:
Random r = new Random();
double randomValue = rangeMin + (rangeMax - rangeMin) * r.nextDouble();
This question was asked before Java 7 release but now, there is another possible way using Java 7 (and above) API:
double random = ThreadLocalRandom.current().nextDouble(min, max);
nextDouble will return a pseudorandom double value between the minimum (inclusive) and the maximum (exclusive). The bounds are not necessarily int, and can be double.
Use this:
double start = 400;
double end = 402;
double random = new Random().nextDouble();
double result = start + (random * (end - start));
System.out.println(result);
EDIT:
new Random().nextDouble(): randomly generates a number between 0 and 1.
start: start number, to shift number "to the right"
end - start: interval. Random gives you from 0% to 100% of this number, because random gives you a number from 0 to 1.
EDIT 2:
Tks #daniel and #aaa bbb. My first answer was wrong.
import java.util.Random;
public class MyClass {
public static void main(String args[]) {
Double min = 0.0; // Set To Your Desired Min Value
Double max = 10.0; // Set To Your Desired Max Value
double x = (Math.random() * ((max - min) + 1)) + min; // This Will Create A Random Number Inbetween Your Min And Max.
double xrounded = Math.round(x * 100.0) / 100.0; // Creates Answer To The Nearest 100 th, You Can Modify This To Change How It Rounds.
System.out.println(xrounded); // This Will Now Print Out The Rounded, Random Number.
}
}
Hope, this might help the best : Random Number Generators in Java
Sharing a Complete Program:
import java.util.Random;
public class SecondSplitExample
{
public static void main(String []arguments)
{
int minValue = 20, maxValue=20000;
Random theRandom = new Random();
double theRandomValue = 0.0;
// Checking for a valid range-
if( Double.valueOf(maxValue - minValue).isInfinite() == false )
theRandomValue = minValue + (maxValue - minValue) * theRandom.nextDouble();
System.out.println("Double Random Number between ("+ minValue +","+ maxValue +") = "+ theRandomValue);
}
}
Here is the output of 3 runs:
Code>java SecondSplitExample
Double Random Number between (20,20000) = 2808.2426532469476
Code>java SecondSplitExample
Double Random Number between (20,20000) = 1929.557668284786
Code>java SecondSplitExample
Double Random Number between (20,20000) = 13254.575289900251
Learn More:
Top 4 ways to Generate Random Numbers In Java
Random:Docs
Random random = new Random();
double percent = 10.0; //10.0%
if (random.nextDouble() * 100D < percent) {
//do
}
The main idea of random is that it returns a pseudorandom value.
There is no such thing as fully random functions, hence, 2 Random instances using the same seed will return the same value in certain conditions.
It is a good practice to first view the function doc in order to understand it
(https://docs.oracle.com/javase/8/docs/api/java/util/Random.html)
Now that we understand that the returned value of the function nextDouble() is a pseudorandom value between 0.0 and 1.0 we can use it to our advantage.
For creating a random number between A and B givin' that the boundaries are valid (A>B) we need to:
1. find the range between A and B so we can know how to many "steps" we have.
2. use the random function to determine how many steps to take (because the returned value is between 0.0 and 1.0 you can think of it as "pick a random percentage of increase"
3. add the offset
After all of that, you can see that mob gave you the easiest and most common way to do so in my opinion
double randomValue = rangeMin + (rangeMax - rangeMin) * r.nextDouble();
double RandomValue = Offset + (Range)*(randomVal between 0.0-1.0)

Categories