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)
Related
This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 6 years ago.
I ran into this problem today and I'm sure there is an elegant solution I am not thinking of.
Let's say I want to generate a random integer(or long) in Java with a specified number of digits, where this number of digits can change.
I.e. pass in a number of digits into a method, and return a random number with the specified number of digits
Ex.) N = 3, generate a random number between 100-999; N = 4, generate a random number between 1000-9999
private long generateRandomNumber(int n){
/*Generate a random number with n number of digits*/
}
My attempt so far (this works, but it seems messy)
private long generateRandomNumber(int n){
String randomNumString = "";
Random r = new Random();
//Generate the first digit from 1-9
randomNumString += (r.nextInt(9) + 1);
//Generate the remaining digits between 0-9
for(int x = 1; x < n; x++){
randomNumString += r.nextInt(9);
}
//Parse and return
return Long.parseLong(randomNumString);
}
Is there a better/more efficient solution than this?
*There are lots of solutions for generating random numbers in a specified range, I was more curious on the best way to generate random numbers given a set number of digits, as well as making the solution robust enough to handle any number of digits.
I did not want to have to pass in a min and max, but rather just the number of digits needed
private long generateRandomNumber(int n) {
long min = (long) Math.pow(10, n - 1);
return ThreadLocalRandom.current().nextLong(min, min * 10);
}
nextLong produces random numbers between lower bound inclusive and upper bound exclusive so calling it with parameters (1_000, 10_000) for example results in numbers 1000 to 9999.
Old Random did not get those nice new features unfortunately. But there is basically no reason to continue to use it anyways.
public static int randomInt(int digits) {
int minimum = (int) Math.pow(10, digits - 1); // minimum value with 2 digits is 10 (10^1)
int maximum = (int) Math.pow(10, digits) - 1; // maximum value with 2 digits is 99 (10^2 - 1)
Random random = new Random();
return minimum + random.nextInt((maximum - minimum) + 1);
}
You can simply disregard the numbers that are not in the required range. That way your modified pseudo random number generator guarantees that it generates a number in the given range uniformly at random:
public class RandomOfDigits {
public static void main(String[] args) {
int nd = Integer.parseInt(args[0]);
int loIn = (int) Math.pow(10, nd-1);
int hiEx = (int) Math.pow(10, nd);
Random r = new Random();
int x;
do {
x = r.nextInt(hiEx);
} while (x < loIn);
System.out.println(x);
}
}
Here is the way I would naturally write a method like this:
private long generateRandomNumber(int n){
double tenToN = Math.pow(10, n),
tenToNMinus1 = Math.pow(10, n-1);
long randNum = (long) (Math.random() * (tenToN - tenToNMinus1) + tenToNMinus1);
return randNum;
}
I am using Ubuntu 14.04.3 LTS and I am studying Java from the book. I tried to follow one example on the book with Ubuntu Terminal and I'm using Sublime Text. Here is the code
import java.util.Scanner;
public class RepeatAdditionQuiz{
public static void main(String[] args){
int number1 = (int)(Math.random()%10);
int number2 = (int)(Math.random()%10);
Scanner input = new Scanner(System.in);
System.out.print(
"What is "+number1+" + "+number2+"?");
int answer = input.nextInt();
while(number1+number2 != answer){
System.out.print("Wrong answer. Try again. What is "
+number1+" + "+number2+"? ");
answer = input.nextInt();
}
System.out.println("You got it!");
}
}
But the problem is, when I compiled it and executed it. It gives me result
what is 0 + 0?_
every time. It suppose to give me random number, and yes, it can be 0. But I tried to run it more than 10 times, it keeps giving me 0 + 0, when it's suppose to random from 0-9.
The result of 0 + 0 is fine when I typed 0 as a result, it gets me out of the loop
Did I miss something to make the math library works? How can I fix the randomize issue?
Math.random() returns a double value between 0 (inclusive) and 1 (exclusive). It does not return an integer value. Therefore, when you take the number produced by Math.random() modulo 10, it returns the same double value. The final cast to int makes that value always 0.
Run the following code to see for yourself:
double random = Math.random();
System.out.println(random); // for example 0.5486395326203879
System.out.println(random % 10); // still 0.5486395326203879
System.out.println((int) (random % 10)); // outputs 0
What you really want is to use a Random object and use Random.nextInt(bound). To have a random integer between 0 and 9, you can use:
Random random = new Random();
int value = random.nextInt(10);
Math.random();
Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
This is the problem. You need to then multiply with 10, so you get a number between 0 and 10 and after that you can cast to int.
public static double random()
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.
(source)
It returns a double that satisfies 0.0 <= double < 1.0, therefore taking the modulo will always result in zero. I recommend the java.util.Random class to achieve what you need. Specifically Random.nextInt(int).
The Math.random() method returns a random double that is from 0 (inclusive) to 1 (exclusive). Performing % 10 doesn't affect this value, but casting it to an int truncates any decimal portion, always yielding 0.
If you want a random number from 0-9, you can multiply Math.random() by 10, instead of taking the remainder when divided by 10.
Alternatively, you can create a java.util.Random object and call nextInt(10).
Read the doc :
Returns a double value with a positive sign, greater than or equal to
0.0 and less than 1.0
Therefore, you will always get less than 1, and the cast to int will round it down to 0. Use, for example, a Random object which has a nextInt(int max) method :
Random rd = new Random();
int number1 = rd.nextInt(10);
int number2 = rd.nextInt(10);
The Math.random() method returns a Double value between 0 and 1, so you will never get a number greater or equal than 1, you will ever get a value that could be 0, but never 1. And as you are taking the residual from this value over 10, you will ever get a 0 as result.
Math.random() % 10 will always be 0, because the random method gives you 0 <= value < 1, and when the % 10 operation takes place, you will get 0.
Check here for more details (oracle documentation)
Math.random() returns a number greater or equal than 0 and less than 1.
What you are looking for is either
int number1 = (int)(Math.random()*10);
int number2 = (int)(Math.random()*10);
or
Random rand = new Random();
int number1 = rand.nextInt(10);
int number2 = rand.nextInt(10);
Also, to get random number from given range, use this for Math.random()
int number 3 = min + (int)(Math.random() * ((max - min) + 1))
and for random.nextInt()
int number 4 = random.nextInt(max - min) + min;
Math.random gives a double value between 0 (incl.)-1 (excl.)!
I want a random number, either 0 or 1 and then that will be returned to main() as in my code below.
import java.util.Scanner;
public class Exercise8Lab7 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numFlips = 0;
int heads = 0;
int tails = 0;
String answer;
System.out.print("Please Enter The Number Of Coin Tosses You Want: ");
numFlips = input.nextInt();
for(int x = 1;x <= numFlips; x++){
if(coinToss() == 1){
answer = "Tails";
tails++;
}
else{
answer = "Heads";
heads++;
}
System.out.print("\nCoin Toss " + x + ": " + answer);
}
System.out.println("\n\n====== Overall Results ======" +
"\nPercentage Of Heads: " + (heads/numFlips)*100 + "\nPercentage Of Tails: " + (tails/numFlips)*100);
}
public static int coinToss(){
double rAsFloat = 1 * (2 + Math.random( ) );
int r = (int)rAsFloat;
return r;
}
}
Many solutions had been suggested to use the util.Random option which I have done and works perfectly but I want to sort out why I can't get this to work. Obviously I want the number to be an int myself so I convert it to an int after the random number has been generated. But no matter what I add or multiply the Math.random() by, it will always all either be Heads or all either be Tails. Never mixed.
Try this) It will generate number 0 or 1
Math.round( Math.random() ) ;
You could use boolean values of 0 or 1 based on value of Math.random() as a double between 0.0 and 1.0 and make the random generator much simpler. And you can get rid completely of the coinToss() method.
if(Math.random() < 0.5) {
answer = "Tails";
tails++;
}
Remove the coin toss method and replace the first conditional with the code above.
Math.random(); by itself will return a value between 0.0 and less than 1.0. If the value is in the lower half, [0.0, 0.5), then it has the same probability of being in the upper half, [0.5, 1.0). Therefore you can set any value in the lower half as true and upper as false.
Wierd that no one is using a modulo division for the random number.
This is the simplest implementation you can get:
Random rand = new Random();
int randomValue = rand.nextInt() % 2;
Math.round(Math.random()) will return either 0.0 and 1.0. Since both these values are well within the limits of int range they can be casted to int.
public static int coinToss(){
return (int)Math.round(Math.random());
}
(int)(Math.random()*2) also works fine in this case
its not working because of the integer math you are using, the call to 2+ Math.Random is pretty much always giving you a answer between 0.0 and 1.0.
so assuming that you recieve 0.25 as your result your maths is as follows
double d = 1* (2 + 0.25); // (result = 2
Then you are checking to see if your result == 1 ( which it never will. )
A better result would be to declare java.util.Random as a class variable and call random.nextBoolean() and simply perform your heads/tails calculation on that.
If you were to continue to use Math.random() and lets say
return Math.random() < 0.5
Your results would be ever so slightly skewed due to the fact that Math.random() cannot return 1.0, due to the fact that the java API specification states:
"Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0."
Math.random() returns a random float in the range [0.0,1.0)--that means the result can be anything from 0 up to but not including 1.0.
Your code
double rAsFloat = 1 * (2 + Math.random( ) );
will take this number in the [0.0,1.0) range; adding 2 to it gives you a number in the [2.0,3.0) range; multiplying it by 1 does nothing useful; then, when you truncate it to an integer, the result is always 2.
To get integers from this kind of random function, you need to figure out how many different integers you could return, then multiply your random number by that. If you want a "0 or 1" answer, your range is 2 different integers, so multiply Math.random() by 2:
double rAsFloat = 2 * Math.random();
This gives you a random number in the range [0.0,2.0), which can then be 0 or 1 when you truncate to an integer with (int). If, instead, you wanted something that returns 1 or 2, for example, you'd just add 1 to it:
double rAsFloat = 1 + 2 * Math.random();
I think you've already figured out that the Random class gives you what you want a lot more easily. I've decided to explain all this anyway, because someday you might work on a legacy system in some old language where you really do need to work with a [0.0,1.0) random value. (OK, maybe that's not too likely any more, but who knows.)
The problem can be translated to boolean generation as follow :
public static byte get0Or1 {
Random random = new Random();
boolean res= random.nextBoolean();
if(res)return 1;
else return 0;
}
Here it the easiest way I found without using java.util.Random.
Blockquote
Scanner input = new Scanner (System.in);
System.out.println("Please enter 0 for heads or 1 for tails");
int integer = input.nextInt();
input.close();
int random = (int) (Math.random() + 0.5);
if (random == integer) {
System.out.println("correct");
}
else {
System.out.println("incorrect");
}
System.out.println(random);
This will take a random double from (0 to .99) and add .5 to make it (.5 to 1.49). It will also cast it to an int, which will make it (0 to 1). The last line is for testing.
for(int i=0;i<100;i++){
System.out.println(((int)(i*Math.random())%2));
}
use mod it will help you!
One more variant
rand.nextInt(2);
As it described in docs it will return random int value between 0 (inclusive) and the specified value (exclusive)
I would like to display the proportion of an initial value in a JProgressBar.
private void updateProgressBars() { //Update the progress bars to the new values.
int p1 = 0, p2 = 1; //Player numbers
double p1Progress = (intPlayer1Tickets/intInitialPlayer1Tickets) * 100;
double p2Progress = (intPlayer2Tickets/intInitialPlayer2Tickets) * 100;
progressbarPlayerTickets[p1].setValue((int) p1Progress);
progressbarPlayerTickets[p1].setString("Tickets left: " + Integer.toString(intPlayer1Tickets));
progressbarPlayerTickets[p2].setValue((int) p2Progress);
progressbarPlayerTickets[p2].setString("Tickets left: " + Integer.toString(intPlayer2Tickets));
}
In this code, the intention was to calculate the percentage of the amount of tickets left a player has. intInitialPlayer1Tickets and intInitialPlayer2Tickets were both set to 50. intPlayer1Tickets and intPlayer2Tickets were then set to their respective initial tickets value (i.e. both set to 50 as well). When I subtract any number from intPlayer1Tickets or intPlayer2Tickets (e.g. intPlayer1Tickets = 49, intInitialPlayer1Tickets = 50), their respective progress bars' value would be set to 0, which is not my intention. Both progress bars have their min and max values set to 0 and 100.
So how would I make it so it would reflect the proportion of tickets left as a percentage?
You are doing integer math and then converting it to a double. In integer math when you divide a number with a number that is bigger, the answer is always 0.
You want to get Java to do your math with floating point numbers rather than with integers. The easiest way to do this is to make your divisor a double.
When you run this code
public class Numbers{
public static void main(String []args){
int five = 5;
int ten = 10;
System.out.println(five/ten);
System.out.println(five/(double)ten);
System.out.println((five/(double)ten)*100);
}
}
You get this as the output
0
0.5
50.0
So, to answer your question what you want is something like this
double p1Progress = (intPlayer1Tickets/(double)intInitialPlayer1Tickets) * 100;
But you'd be just fine using float for this instead of doubles.
Cast the value of intPlayer1Tickets, intPlayer2Tickets, intInitialPlayer1Tickets and intInitialPlayer2Tickets to double before you calculate. As in:
double p1Progress = (((double) intPlayer1Tickets)/((double) intInitialPlayer1Tickets)) * 100;
double p2Progress = (((double) intPlayer2Tickets)/((double) intInitialPlayer2Tickets)) * 100;
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);