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 am trying to print a random number between 80 and 100.
However when I print out this number I am getting numbers over 100?
Random num = new Random();
int percent = 80 + num.nextInt(100);
System.out.println(percent);
Can you try something like this
There are two approach below
int resultNumber = ThreadLocalRandom.current().nextInt(80, 100 + 1);
System.out.println(resultNumber);
Random num = new Random();
int min =80;
int max=100;
System.out.println(num.nextInt(max-min) + min);
Explanation
From the documentation of Random#nextInt(int):
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), [...]
So your call
num.nextInt(100);
Generates numbers between 0 (inclusive) and 100 (exclusive). After that you add 80 to it. The resulting range for your percent is thus 80 (inclusive) to 180 (exclusive).
Solution
In order to get a number from 80 to 100, what you actually want to do is to generate a number from 0 to 20 and add that on top of 80. So
int percent = 80 + num.nextInt(20);
The general formula is
int result = lowerBound + random.nextInt(upperBound - lowerBound);
Notes
Favor using ThreadLocalRandom over new Random(), it is faster because it sacrifices thread-safety (which you most likely do not need). So:
Random num = ThreadLocalRandom.current();
It actually also has an additional nextInt(int, int) method for exactly this use case. See the documentation:
Returns a pseudorandom int value between the specified origin (inclusive) and the specified bound (exclusive).
The code would then just be:
int percent = ThreadLocalRandom.current().nextInt(80, 100);
All my examples so far assumed that 100 is exclusive. If you want it to be inclusive, just add 1 to it. So for example
int percent = ThreadLocalRandom.current().nextInt(80, 101);
Related
This question already has answers here:
Getting N random numbers whose sum is M
(9 answers)
Closed 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
my output contains 3 textfields where when given N value (the doClick() function clicks 3 textfields automatically), then it randomly generates 3 numbers in the three textfields , My code is generating only random numbers , but i want those randomly generated numbers to be exactly add up to given N.
example : when N=20
then possible answers can be:
1.10,10,0 i.e. (textfield1 show 10, textfield2 show 10, textfiled3 show 0, whose sum adds up to given N )
2.15,3,2
3.10,5,5
random numbers can be any positive integer but it should add up to given N.
Any help please.
You could use Math.random() instead of the Random class. Math.random() returns a double between 0 and 1. So the only thing you have to do is multiply the result of Math.random() with N. The next number would be N minus your result from the subtraction of N and the previous result.
final int N = 20;
final int result0 = (int) (Math.random() * N);
final int result1 = (int) (Math.random() * (N - result0));
final int result2 = N - result0 - result1;
EDIT: You could than choose the first, second and third parameter randomly too.
Is there a difference between
int number = (int) (Math.random() * 1000);
and
int number = (int)(100 + Math.random() * 900);
for generating a random 3-digit number?
Your second expression guarantees to produce a 3-digit random number but the first one does not guarantee it. The first expression can produce any integer from 0 to 999.
You can also produce a 3-digit random integer as follows:
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random random = new Random();
int number = random.nextInt(900) + 100;
System.out.println(number);
}
}
Math.random() from Java API:
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.
For example:
// Generate random number
double rand = Math.random();
// Output is different everytime this code is executed
System.out.println("Random Number:" + rand);
//pseudorandom output: 0.5568515217910215
In your case:
int number = (int) (Math.random() * 1000); returns anything between 0 - 999
int number = (int)(100 + Math.random() * 900); returns anything between 100 - 999
More information from Java API
When this method is first called, it creates a single new pseudorandom-number generator, exactly as if by the expression
new java.util.Random()
This new pseudorandom-number generator is used thereafter for all calls to this method and is used nowhere else.
This method is properly synchronized to allow correct use by more than one thread. However, if many threads need to generate pseudorandom numbers at a great rate, it may reduce contention for each thread to have its own pseudorandom-number generator.
So the bottom line is:
Math.random() returns a pseudorandom double greater than or equal to 0.0 and less than 1.0.
In this kind of questions you should visit Java API instead. Hope it helped!
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 am trying to generate a random number between a given range and 0.
The code given below helped me to generate a number between the given range.
(int)(Math.random() * 13 + 4);
Is it possible to modify this code to generate a value between 4 and 10 and also 0
use this for generate a value between 4 and 10
public static double getRandomDoubleBetweenRange(int 4, int 10){
double x = (Math.random()*((10-4)+1))+4;
return x;
}
I suspect that this is a homework question so I won't spoonfeed you with the correct answer but give you the tools you need to answer it yourself:
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: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#random--
Casting a double to an int performs a narrowing primitive conversion. In the range you use and for positive numbers, you can just treat it like a floor (removing the numbers after the decimal point).
If you want to know about the details, see: https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.3
Something like this would do the cause.
//stream 3 random numbers from 0 to 10 and pick any of them
int random = new Random().ints(3, 0, 11).findAny().getAsInt();
//print it
System.out.println(random);
UPDATE 2:
// make a list of 0 and 4-10
List<Integer> list = Arrays.asList(0,4,5,6,7,8,9,10);
// used for picking random number from within a list
Random random = new SecureRandom();
// get random index element from a list
int randomNumber = list.get(random.nextInt(list.size()));
// print
System.out.println(randomNumber);
This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 3 years ago.
double random1 = Math.random() * 9 + -9;
double random2 = Math.random() * -9 + 9;
I need randomly generated numbers ranging from -9 to 9 using Math.random. When I use this code I have here it only prints the first number as a negative number.I've ran this multiple times and still the first number is always negative while the second is positive. How can I fix this to be more random? Thanks
Math.random() generates a number between 0 and 1.
How about multiplying by 18 and then subtracting 9?
From jdk-7 you can use ThreadLocalRandom
public int nextInt(int origin, int bound)
Returns a pseudorandom int value between the specified origin (inclusive) and the specified bound (exclusive).
ThreadLocalRandom.current().nextInt(-9, 10) // will generate from -9>=x<10
When you want a value between a number min and a number max :
Math.random() * ((max - min) + 1) + min
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Generate random number with non-uniform density
I try to identify/create a function ( in Java ) that give me a nonuniform distributed sequence of number.
if I has a function that say function f(x), and x>0 it will give me a random number
from 0 to x.
The function most work with any given x and this below is only a example how I want to have.
But if we say x=100 the function f(x) will return s nonunifrom distributed.
And I want for example say
0 to 20 be approximately 20% of all case.
21 to 50 be approximately 50% of all case.
51 to 70 be approximately 20% of all case.
71 to 100be approximately 10 of all case.
In short somting that give me a number like normal distribution and it peek at 30-40 in this case x is 100.
http://en.wikipedia.org/wiki/Normal_distribution
( I can use a uniform random gen as score if need, and only a function that will transfrom the uniform result to a non-uniform result. )
EDIT
My final solution for this problem is:
/**
* Return a value from [0,1] and mean as 0.3, It give 10% of it is lower
* then 0.1. 5% is higher then 0.8 and 30% is in rang 0.25 to 0.45
*
* #return
*/
public double nextMyGaussian() {
double d = -1000;
while (d < -1.5) {
// RANDOMis Java's normal Random() class.
// The nextGaussian is normal give a value from -5 to +5?
d = RANDOM.nextGaussian() * 1.5;
}
if (d > 3.5d) {
return 1;
}
return ((d + 1.5) / 5);
}
A simple solution would be to generate a first random number between 0 and 9.
0 means the 10 first percents, 1 the ten following percents, etc.
So if you get 0 or 1, you generate a second random number between 0 and 20. If you get 2, 3, 4, 5 or 6, you generate a second random number between 21 and 50, etc.
Could you just write a function that sums a number of random numbers it the 1-X range and takes an average? this will tend to the normal distribution as n increases
See:
Generate random numbers following a normal distribution in C/C++
I hacked something like the below:
class CrudeDistribution {
final int TRIALS = 20;
public int getAverageFromDistribution(int upperLimit) {
return getAverageOfRandomTrials(TRIALS, upperLimit);
}
private int getAverageOfRandomTrials(int trials, int upperLimit) {
double d = 0.0;
for (int i=0; i<trials; i++) {
d +=getRandom(upperLimit);
}
return (int) (d /= trials);
}
private int getRandom(int upperLimit) {
return (int) (Math.random()*upperLimit)+1;
}
}
There are libraries in Commons-Math that can generate distributions based on means and standard deviations (that measure the spread). and in the link some algorithms that do this.
Probably a fun hour of so of hunting to find the relevant 2 liner:
https://commons.apache.org/math/userguide/distribution.html
One solution would be to do a random number between 1-100 and based on the result do another random number in the appropriate range.
1-20 -> 0-20
21-70 -> 21-50
71-90 -> 51-70
91-100 -> 71-100
Hope that makes sense.
You need to create the f(x) first.
Assuming values x are equiprobable, your f(x) is
double f(x){
if(x<=20){
return x;
}else if (x>20 && x<=70){
return (x-20)/50*30+20;
} else if(...
etc
Just generate a bunch, say at least 30, uniform random numbers between 0 and x. Then take the mean of those. The mean will, following the central limit theorem, be a random number from a normal distribution centered around x/2.