Generation a random number between 50% and 150% [duplicate] - java

This question already has answers here:
Generate a random double in a range
(7 answers)
Closed 6 years ago.
I have:
private Random rng = new Random();
double random = rng.nextDouble(1.5-0.5) + 0.5;
Because I want to generate a number between 50% and 150%. However it throws me an error. How do I get a number in that range using the random function?

Your problem is: you should read javadoc. Meaning: dont assume that some library method does something; instead: read the documentation to verify that your assumptions are correct.
In this case, check out Double.nextDouble ... and find:
Returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator's sequence.
The point is: there is no method nextDouble() that takes a double argument! There is only one that goes without any argument; and that method by default returns a value between 0 and 1.
So, simply change your code to call that method without any argument!

That is because nextDouble does not receive parameters, and only return a double between 0.0 and 1.0. Use the following:
Random rng = new Random();
double max = 1.5;
double min = 0.5;
double random = rng.nextDouble(); // Double between 0.0 and 1.0
double percentage = random*(max-min) + min;
System.out.println(percentage);

If you read the error in the ide or just look at the java doc you will see clearly the reason...
method nextDouble() in the type Random is not applicable for the
arguments (double)
the random class has no such a method nextDouble() that takes a double as argument
BTW why don't you just generate a random integer between 50 and 150... that would make more sense for the implementation you desire...
something like
Random rand = new Random();
randomNum = minimum + rand.nextInt((maximum - minimum) + 1);

You can do something like 50% and 100%
public static void main(final String[] args) {
Random rng = new Random();
double random = rng.nextDouble();
if (random <= 0.5) {
System.out.println("50% " + random);
} else {
System.out.println("100% " + random);
}
}

Related

How do these 2 random values differ?

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!

Generating a number between a given range and 0 [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 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);

Random double and gaussian distribution

I want to generate double numbers [-25,+25] but it does not work for me!.
I used this code :
//=============== method set random individuals (genes)======================
public void rand_gene() {
double rand = new Random().nextDouble();
for (int i=0 ;i<size;i++) {
this.setGene(i, -25+(rand));
System.out.print(genes[i]+" ");
} }
and I want to round it to 2 numbers after coma.
any help ?
The most fundamental problem with your code is that you are generating a single random value and using it for all i. But your code has other problems as well.
A Gaussian (a.k.a. normal) distribution has infinite tails, so if you want the random variable to be restricted to [-25, +25], it can't be a Gaussian distribution. The typical approach is to use a truncated normal distribution. There are several libraries that generate such random variables, which you can find with a web search. I'd start with a look at the Stochastic Simulation in Java library, or perhaps Broadwick (in particular their TruncatedNormalDistribution class).
A poor-man's approximation is to use a simple sample-reject algorithm with a normal distribution generator, as below.
The other issue—that you want values rounded to 2 decimal places—is easily accomplished by multiplying by 100, rounding to the nearest integer, and then dividing by 100.
Here's my take on doing what you want:
// initialize a random number generator
// for production work, consider using a better RNG than java.util.Random
private Random rng = new Random();
private double sigma = /* desired standard deviation */
public void rand_gene() {
for (int i = 0; i < size; ++i) {
setGene(i, nextRand());
}
}
/** Return a random Gaussian in the range [-25, +25] */
private double nextRand() {
double val;
do {
val = sigma * rng.nextGaussian();
val = Math.round(val * 100) / 100.0;
} while (val < -25 || val > 25);
return val;
}

Set accuracy of random numbers in java?

I was wondering if I am able to set the accuracy of the random double numbers that I generate.
Random generator = new Random();
double randomIndex = generator.nextDouble()*10000;
That produces the random numbers within 10000.
How am I able to set the accuracy to 4?
A couple of things. First, you mean "precision", not "accuracy". Second, you need to clarify why you want to do this, because a correct answer will depend on it.
If all you want to do is display the numbers with that precision, it is a formatting issue. You can use, e.g. System.out.printf("%.4f", value) or String.format().
If you are trying to to generate numbers with that precision, you could approximate by doing something like (rounding left out for simplicity):
double value = (int)(generateor.nextDouble() * 10000.0) / 10000.0;
Or if you want your range to be 0-10000 instead of 0-1:
double value = (int)(generateor.nextDouble() * 100000000.0) / 10000.0;
Due to the way floating-point numbers are stored, that will not be exact, but perhaps it is close enough for your purposes. If you need exact, you would want to store as integers, e.g.:
int value = (int)(generator.nextDouble() * 10000.0);
Then you can operate on that internally, and display as:
System.out.printf("%.4f", value / 10000.0);
Adjust multiplication factor above if you meant you wanted your range to be 0-10000.
If you are merely trying to generate a number in [0, 10000), you can use Random.nextInt(int) with a range specified, or simply cast the value to an int as above (optionally rounding).
Random generator = new Random();
double randomIndex = generator.nextDouble()*10000;
randomIndex=Math.floor(randomIndex * 10000) / 10000;//this is the trick
If you want 4 digits after the decimal mark you can simply do the following:
Random generator = new Random();
double randomIndex = Math.floor(generator.nextDouble()*10000 * 10000) /10000;
Random generator = new Random();
double randomIndex = Double.parseDouble(new DecimalFormat("##.####")
.format(generator.nextDouble() * 10000));
Simply
double result = generator.nextLong() / 10000.0;
Note, hoewever, that you can never be sure that the number has exactly 4 decimals, whenever you hit a number that is not representable in a double.
Anyway, the requirement is silly, because a double simply does not have decimal positions. Hence, to request 4 of them makes no sense.

Java random numbers not random?

I was trying to explain the random number generator in Java to a friend when he kept getting the same numbers every time he ran the program. I created my own simpler version of the same thing and I too am getting the same exact numbers he was getting every time I run the program.
What am I doing wrong?
import java.util.*;
public class TestCode{
public static void main(String[] args){
int sum = 0;
Random rand = new Random(100);
for(int x = 0; x < 100; x++){
int num = (rand.nextInt(100)) + 1;
sum += num;
System.out.println("Random number:" + num);
}
//value never changes with repeated program executions.
System.out.println("Sum: " + sum);
}
}
The final five numbers out of the 100 are:
40
60
27
56
53
You have seeded the random generator with a constant value 100. It's deterministic, so that will generate the same values each run.
I'm not sure why you chose to seed it with 100, but the seed value has nothing to do with the range of values that are generated (that's controlled by other means, such as the call to nextInt that you already have).
To get different values each time, use the Random constructor with no arguments, which uses the system time to seed the random generator.
Quoting from the Javadoc for the parameterless Random constructor:
Creates a new random number generator. This constructor sets the seed
of the random number generator to a value very likely to be distinct
from any other invocation of this constructor.
Quoting the actual code in the parameterless Random constructor:
public Random() {
this(seedUniquifier() ^ System.nanoTime());
}
This:
Random rand = new Random(100);
You're giving the random number generator the same seed (100) each time you start the program. Give it something like the output from System.currentTimeMillis() and that should give you different numbers for each invocation.
Random number generators are really only pseudo-random. That is, they use deterministic means to generate sequences that appear random given certain statistical criteria.
The Random(long seed) constuctor allows you to pass in a seed that determines the sequence of pseudo-random numbers.
Please see the below code to generate a random number from a pool of random numbers.
Random r = new Random(System.currentTimeMillis());
double[] rand = new double[500];
for(int i=0;i<100;i++){
rand[i] = r.nextDouble();
}
double random_number = rand[randomInt];

Categories