I would like to generate the numbers 1-4 (whole integers) using Math.random. I have only succeeded in getting doubles or large doubles, and cannot figure out how to set a limit on the minimum and maximum.
Math.random(); = something between 0-1 as a double?
I have seen some people suggest something like this: num = Math.random() * 60 + 25; but have no idea what that does, or how it works.
I am not sure if this is a true question, and feel free to let me know if I should delete it.
Edit: Is there a way to not get the numbers to repeat, yet still be random every time the program is run?
int rand = (Math.random() * 4) + 1;
Math.Random is redundant here, use the Random class.
Random rand = new Random();
rand.nextInt(4)+1; //starts at 0, so add 1
Import this class by:
import java.util.*; or import java.util.Random;
the random number in math gives you a decimal number between zero and one.
you need to tell it to be within a certain range.
something like:
(4*Math.random())+1 should give you between 1-4 I think. correct me if I am wrong anyone.
Random rand = new Random();
System.out.println(rand.nextInt(4) + 1); // we add 1 because it starts with 0
If you really have to use Math.random you need to multiply (and add).
It's quite basic math, Math.random()
Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
So multiplying it with X will give a number greater than or equal to 0.0 and less than X. Cast that to an int to get rid of decimals and if you only want even numbers you can do a few things, the easiest probably being int even = (notSureIfEven >> 1) << 1;. [I'm kind of assuming that with 'even' numbers you actually meant 'whole' numbers though, in which case you can ignore that.] Then if you don't want the range to be 0->X but Y->X you just add Y to your outcome (make sure to subtract Y from X before the multiplication or your range will be Y->X+Y).
To not generate the same number twice you can do different things. One way is to store all the numbers you generated so far in a List and then when you generate a new number, check if the list contains that number already, if so generate a new one until you got one that isn't in the list (and then when you do obviously add that to the list). Another way could be to preload all numbers it could generate into a list and then remove a random number out of that list.
Both ways probably won't scale very well to really large ranges of numbers though. The first one since it might get in a very long loop trying to find a number it hadn't generated yet, the second one because you'll have to create a really large list at the start.
I'm not sure if there's something you could do in the case of a really large range.
Related
I am trying to implement a random number generator in my Java program. I was using Math.random() but that didn't seem to work very well. Then I tried using SecureRandom, but that took too long for my game. However, I came across this generator, the MersenneTwisterRNG random number generator. It seems to be what I want; fast, but still random.
However, I have not been writing in Java for very long, only 2 months, and I cannot make heads nor tails of the API. If anyone could help explain to me how to use this in my code, it would be appreciated. Or, if you happen to know of a simpler, but similar, random number generator, I would be interested in that as well. The API is here.
How to use the MersenneTwisterRNG API:
import java.util.Random;
import org.uncommons.maths.random.MersenneTwisterRNG;
This lets you access the classes using their short names.
Random rand = new MersenneTwisterRNG();
This creates a new MersenneTwisterRNG. We put it into a variable of type Random so that we can swap it out for another RNG easily if needed.
double x = rand.nextDouble();
This behaves the same as Math.random(), and returns a double-precision floating-point number between 0.0 and 1.0.
int n = rand.nextInt(10);
This generates a random number between 0 (inclusive) and 9 (inclusive), i.e. 0 <= n < 10. This is useful for a lot of integer algorithms.
I have seen MANY posts on here in regard to generating random numbers with a specific range in JAVA (especially this one). However, I have not found one that describes how to generate a random number between a negative MAX and a negative MIN. Is this possible in Java?
For example, if I want to generate a random number that is between (-20) and (-10). Using something like the below will only result in a JAVA Exception that screams about n having to be positive:
int magicNumber=(random.nextInt(-20)-10);
Just generate a random number between 10 and 20 and then negate it.
Another option would be to generate a random number between 0 and 10 and then subtract 20, if that feels less like a work-around to you.
I'm not entirely sure what you want, but ThreadLocalRandom has a method which accepts a range, which can also have negative values:
ThreadLocalRandom.current().nextInt(-20, -10 + 1)
There is no practical difference to just negating the result of a positive random though.
So I am making an application that can solve problems with Empirical Formulae and I need some code that would do something like:
If numbers are 2.5, 1, 3 it should change them to 2.5*2 = 5, 1*2 = 2, 3*2 = 6 so that the number with the decimal is converted to a whole number and the other numbers are adjusted appropriately.
I thought of this logic:
for(n = 1; (Math.round(simplestRat[0]) * n) != (int)SimplestRat[0]; n++)
to increment a counter that would multiply an integer to do what I want it to but I am skeptical about this code even at this phase and do not think it will work.
It would be a lot of help if someone could suggest a code for this or improve upon this code or even give me a link to another post for this problem as I was unable to find anything regarding this type of problem.
Any help is appreciated. Thanks
Okay, so you have to have a few steps. First, get them all into whole numbers. The easiest way is to find an appropriate power of ten to multiply them all by that leaves them as integers. This is a useful check: How to test if a double is an integer.
Then cast them to integers, and start working through them looking for common prime factors. This'll be a process similar to Eratosthenes' Sieve (http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) but with division at the end. For each prime, see if all 3 numbers divide by it exactly (modulo prime == 0). If they do, divide and reset the primes to 2. If they don't, next prime.
This should give you the lowest common ratio between the numbers. Any additional multiplier that came from the original stage is shaved off by the common primes method.
I would like to select one of three numbers with equal probability (33.3%). Can I use the Random class to achieve this?
What would be the percentage of each number being selected after 100x running? Would it be evenly 33.3% each?
Use the Random.nextInt(n) method to select a number between 0 and 2. Use this to choose one of your three values.
int index = Random.nextInt(3);
int selectedValue = myOptions[index];
The value returned by that method is uniformly distributed. So if you were to repeat this process infinitely, the probability of each number being chosen would approach 1/3.
From the docs:
All n possible int values are produced with (approximately) equal probability
You can try somethin like this for 1/25 probabilty
if(new java.util.Random().nextInt(25)==0){
//Do something.
}
Random rand = new Random();
int number = rand.nextInt(3) + 1;
Note that there is no such thing as true random. In computer science, we use so called pseudo-randomness. For most everyday purposes that's close enough to random that the difference isn't noticable. You say you'll be running it 100 times, then yes. For all intents and purposes it will be 33.3333...%.
You need to decide whether entropy is more important than 'randomnes'. Randomness will not give you a perfect 33.3% but the final outcome will be unpredictable. Other algorithms can give you a perfect 33.3% but the outcome can be predictable, and even the same in some cases each time the process is ran.
it is possible for exact random ness for only a two value range.
....after random statemeants...
if(rand=>1&&rand<=1.4999999999999999999999....)
{
rand=1;
}
else
{
rand=2
}
I have a simple code which generates random numbers
SecureRandom random = new SecureRandom();
...
public int getRandomNumber(int maxValue) {
return random.nextInt(maxValue);
}
The method above is called about 10 times (not in a loop). I want to ensure that all the numbers are unique (assuming that maxValue > 1000).
Can I be sure that I will get unique numbers every time I call it? If not, how can I fix it?
EDIT: I may have said it vaguely. I wanted to avoid manual checks if I really got unique numbers so I was wondering if there is a better solution.
There are different ways of achieving this and which is more appropriate will depend on how many numbers you need to pick from how many.
If you are selecting a small number of random numbers from a large range of potential numbers, then you're probably best just storing previously chosen numbers in a set and "manually" checking for duplicates. Most of the time, you won't actually get a duplicate and the test will have practically zero cost in practical terms. It might sound inelegant, but it's not actually as bad as it sounds.
Some underlying random number generation algorithms don't produce duplicates at their "raw" level. So for example, an algorithm called a XORShift generator can effectively produce all of the numbers within a certain range, shuffled without duplicates. So you basically choose a random starting point in the sequence then just generate the next n numbers and you know there won't be duplicates. But you can't arbitrarily choose "max" in this case: it has to be the natural maximum of the generator in question.
If the range of possible numbers is small-ish but the number of numbers you need to pick is within a couple of orders of magnitude of that range, then you could treat this as a random selection problem. For example, to choose 100,000 numbers within the range 10,000,000 without duplicates, I can do this:
Let m be the number of random numbers I've chosen so far
For i = 1 to 10,000,000
Generate a random (floating point) number, r, in the range 0-1
If (r < (100,000-m)/(10,000,000-i)), then add i to the list and increment m
Shuffle the list, then pick numbers sequentially from the list as required
But obviously, there's only much point in choosing the latter option if you need to pick some reasonably large proportion of the overall range of numbers. For choosing 10 numbers in the range 1 to a billion, you would be generating a billion random numbers when by just checking for duplicates as you go, you'd be very unlikely to actually get a duplicate and would only have ended up generating 10 random numbers.
A random sequence does not mean that all values are unique. The sequence 1,1,1,1 is exactly as likely as the sequence 712,4,22,424.
In other words, if you want to be guaranteed a sequence of unique numbers, generate 10 of them at once, check for the uniqueness condition of your choice and store them, then pick a number from that list instead of generating a random number in your 10 places.
Every time you call Random#nextInt(int) you will get
a pseudorandom, uniformly distributed int value between 0 (inclusive)
and the specified value (exclusive).
If you want x unique numbers, keep getting new numbers until you have that many, then select your "random" number from that list. However, since you are filtering the numbers generated, they won't truly be random anymore.
For such a small number of possible values, a trivial implementation would be to put your 1000 integers in a list, and have a loop which, at each iteration, generates a random number between 0 and list.size(), pick the number stored at this index, and remove it from the list.
This is code is very efficient with the CPU at the cost of memory. Each potiental value cost sizeof(int) * maxValue. An unsigned integer will work up to 65535 as a max. long can be used at the cost of a lot of memory 2000 bytes for 1000 values of 16 bit integers.
The whole purpose of the array is to say have you used this value before or not 1 = yes
'anything else = no
'The while loop will keep generating random numbers until a unique value is found.
'after a good random value is found it marks it as used and then returns it.
'Be careful of the scope of variable a as if it goes out of scope your array could erased.
' I have used this in c and it works.
' may take a bit of brushing up to get it working in Java.
unsigned int a(1000);
public int getRandomNumber(int maxValue) {
unsigned int rand;
while(a(rand)==1) {
rand=random.nextInt(maxValue);
if (a(rand)!=1) { a(rand)=1; return rand;}
}
}