I am using java.util.random with a seed(new Random(System.currentTimeMillis())
I need to convert this to a int(my business logic)
I tried using the .nextInt(), but it doesn't help
//my business logic--Below code is in a loop and is intended to
generate a different random number each time//
int randomNumber=(int) Math.floor(inputParam1 * (new Random(System.currentTimeMillis())).nextInt()));
Expected Ouput:A new random number to be generated each time, in int format
Actual Output:
- with nextInt() it is generating the same number each time
- without converting to Int, I am not able to use the 'Random'
datatype with my int variable shown above
Don't create a new instance of Random each time you want to generate a Double.
You can create one instance and then call it whenever you need a new double.
Random rand = new Random(System.currentTimeMillis());
// loop starts here
double randomNumber = Math.floor(inputParam1 * rand.nextDouble());
// If you want an integer up to inputParam1 as it seems, you can do:
int randomInt = (int) randomNumber;
You can also use Math.random() as someone already suggested.
I am not sure why are you casting it to int
double randomNumber= new Random(System.currentTimeMillis()).nextDouble();
this will give a random double number between 0 and 1
Converting below code to int makes no sense.
Math.floor(inputParam1 * (new Random(System.currentTimeMillis())).nextDouble()))
And please, check this answer Using Random Number Generator with Current Time vs Without
The most important part from above link:
If you want your random sequences to be the same between runs you can
specify a seed.
Related
I have to generate unique serial numbers for users consisting of 12 to 13 digits. I want to use random number generator in Java giving the system. Time in milliseconds as a seed to it. Please let me know about the best practice for doing so. What I did was like this
Random serialNo = new Random(System.currentTimeMillis());
System.out.println("serial number is "+serialNo);
Output came out as: serial number is java.util.Random#13d8cc98
For a bit better algorithm pick SecureRandom.
You passed a seed to the random constructor. This will pick a fixed sequence with that number. A hacker knowing the approximate time of calling, might restrict the number of attempts. So another measure is not using the constructor and nextLong at the same spot.
SecureRandom random = new SecureRandom​();
long n = random.nextLong();
A symmetric bit operation might help:
n ^= System.currentMillis();
However there is a unique number generation, the UUID, a unique 128 bits number, two longs. If you xor them (^) the number no longer is that unique, but might still be better having mentioned the circumstantial usage of random numbers.
UUID id = UUID.randomUUID();
long n = id.getLeastSignificantBits() ^ id.getMostSignificantBits();
Create a random number generator using the current time as seed (as you did)
long seed = System.currentTimeMillis();
Random rng = new Random​(seed);
Now, to get a number, you have to use the generator, rng is NOT a number.
long number = rng.nextLong();
According to the documentation, this will give you a pseudorandom number with 281.474.976.710.656 different possible values.
Now, to get a number with a maximum of 13 digits:
long number = rng.nextLong() % 10000000000000;
And to get a number with exactly 13 digits:
long number = (rng.nextLong() % 9000000000000) + 1000000000000;
First, import the Random class:
import java.util.Random;
Then create an instance of this class, with the current milliseconds as its seed:
Random rng = new Random(System.currentTimeMillis());
This line would generate an integer that can have up to 13 digits:
long result = rng.nextLong() % 10000000000000;
This line would generate an integer that always have 13 digits:
long result = rng.nextLong() % 9000000000000 + 1000000000000;
There are three ways to generate Random numbers in java
java.util.Random class
We can generate random numbers of types integers, float, double, long, booleans using this class.
Example :
//Random rand = new Random();
// rand_int1 = rand.nextInt(1000)
Math.random method : Can Generate Random Numbers of double type.
random(), this method returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
Example :
Math.random());
//Gives output 0.15089348615777683
ThreadLocalRandom class
This class is introduced in java 1.7 to generate random numbers of type integers, doubles, booleans etc
Example :
//int random_int1 = ThreadLocalRandom.current().nextInt();
// Print random integers
//System.out.println("Random Integers: " + random_int1);
When you have imported java.util.Random, you can both generate random integers and random double two ways.
You could create an instance of the Random class
Random randomGenerator = new Random();
and then use it to generate a random integer or double that is greater than or equal to 0 but less than 10
int randomInteger = randomGenerator.nextInt(10);
double randomDouble = randomGenerator.nextDouble(10);
You can also use Math.random()
int randomInteger = (int)(Math.random() * 10)
double randomDouble = Math.random() * 10
I think both methods gives the exact same result.
Is one of these two methods ever preferred rather than the other?
Math.random() uses the Random class. And it's basically calling nextDouble() on the Random object of the Math class.
However the first method is definitely easier to understand and use. And has more options then the Math class has. So I'd go with the Random class if you need a lot of Random numbers or if you need types other then double. And I'd use Math.random() when you only need a double between 0 and 1.
So basically there is no difference in how the methods work, they both use the Random class. So wich of the two you use depends on the situation as I stated above.
From the javadoc for the Math class on the random method:
When this method is first called, it creates a single new pseudorandom-number generator, exactly as if by the expression
new java.util.Random()
Link to the javadoc page on Math.random(): https://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#random()
I hope this helps :)
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.
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];
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java random number with given length
I have been trying to generate a 15 digit long number in java but it seems I have failed to do it so far as using:
This is producing a maximum of 10 digits.
Random random = new Random();
int rand15Digt = random.nextInt(15);
How can I generate it successfully?
Use Random's method public long nextLong()
To begin with, an int can hold numbers between -2,147,483,648 and 2,147,483,647.
Use Random.nextLong()
Any number can be formatted into 15 decimal digits when presented as a string. This is achieved when the number is converted to a String, e.g.:
System.out.println(String.format("%015d", 1));
// prints: 000000000000001
If you want to generate a random number that lies between 100,000,000,000,000 and 999,999,999,999,999 then you can perform a trick such as:
Random random = new Random();
long n = (long) (100000000000000L + random.nextFloat() * 900000000000000L);
If your ultimate goal is to have a 15-character string containing random decimal digits, and you're happy with third-party libraries, consider Apache commons RandomStringUtils:
boolean useLetters = false;
boolean useNumbers = true;
int stringLength = 15;
String result = RandomStringUtils.random(stringLength, useLetters, useNumbers)
What about trying BigInteger, see this StackOverflow link for more information Random BigInteger Generation
In Hibernate have UUIDGenerator class using this we can create Secure Random and Unique Number also.
public Serializable generate(SessionImplementor session, Object object)
throws HibernateException {
String uuid = (String)super.generate(session, object);
return uuid.substring(uuid.length()-15, uuid.length());
}
i think this is best way to Generate Unique and also Random Number...