However, conversely with ThreadLocalRandom there is no way to explicitly set the seed so it can be difficult to reproduce results in situations where that is useful such as testing or saving game states or similar.
As of Java 17, the psuedorandom number generating classes in the standard library implement the RandomGenerator interface. See the linked JavaDoc for more information. For example, if a cryptographically strong random number generator is desired, the SecureRandom class can be used.
But, this still doesn't include Max and you are getting a double value. In order to get the Max value included, you need to add 1 to your range parameter (Max - Min) and then truncate the decimal part by casting to an int. This is accomplished via:
ThreadLocalRandom equivalent of class java.util.Random for multithreaded environment. Generating a random number is carried out locally in each of the threads. So we have a better performance by reducing the conflicts.
For fork join pools and parallel streams, use SplittableRandom (it implements SplittableGenerator interface, see Java 17 notes below) that is usually faster, has a better statistical independence and uniformity properties in comparison with Random.
It is recommended that multithreaded applicationsuse either ThreadLocalRandom or (preferably) pseudorandom numbergenerators that implement the RandomGenerator.SplittableGenerator orRandomGenerator.JumpableGenerator interface.
1 - RandomGenerator is a modern interface that was introduced in Java 17. It is a common protocol for objects that generate random or pseudorandom sequences of numbers and has more features and methods than Random.
This gives you a random number in between 1 (inclusive) and 11 (exclusive), so initialize the upperBound value by adding 1. For example, if you want to generate random number between 1 to 10 then initialize the upperBound number with 11 instead of 10.
The RandomGenerator interface was also added to the existing random generation classes (Random, SecureRandom, SplittableRandom, and ThreadLocalRandom). Therefore, as of Java 17, those four classes also have this bounded nextInt method:
David De wrote:Got it, thank you.
The last thing in this little program is how can I make each IF statement jump to the random number generator? This only works if they user types in anything but Mike or David. I would like it to go to the random number generator regardless. Is this what is called a method?
Most languages like Java and Go, come with standard pseudo-random-number generators. Java uses a simple linear congruential generator. Starting with a seed value, it generates a new value with the reccurence formula:
Choosing the correct pseudo-random number generator for a Monte Carlo simulation requires a careful analysis, but as a rule of thumb linear congruential generators (LCG) are inadequate. (At least if you are doing computational science, and not video games. This is not because computational science is a more noble endeavour than video game developing: the simulation of physical systems has different requirements than the simulation of a synthetic world. )
This kind of thing is exactly why I think threads should be used approximately never by applications. Non-parallel abstractions (events, coroutines, coop threads, etc) for multitasking, and pools of worker processes for parallelism! That way be default you never have to worry about the memory nightmares that lead to by-default thread safe RNGs.
Goroutines are just dressed-up threads. The Go community promotes a CSP style of programming with channels, but you can share memory between goroutines and get data races just like you can in Java or C (or almost any other popular language these days).
FYI, Erlang/OTP PRNGs in rand module has three algorithms: Xorshift116+ as default, Xorshift64* and Xorshift1024* are the other choices. Seeds must be given explicitly, or chosen to use the one stored in the process dictionary (a per-process storage area). Note in Erlang processes are roughly equivalent to C or Java threads, but each process has its own dictionary, not sharable with other processes.
This allows you to carry out concurrent work but recreate the original state from a seed, since you can use this to handle non-determinism. And it allows you to use the same RNG for a binary tree, but cut off a subtree without having to roll forward the RNG state. You just split at each node.
If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers. In order to guarantee this property, particular algorithms are specified for the class Random. Java implementations must use all the algorithms shown here for the class Random, for the sake of absolute portability of Java code. However, subclasses of class Random are permitted to use other algorithms, so long as they adhere to the general contracts for all the methods. The algorithms implemented by class Random use a protected utility method that on each invocation can supply up to 32 pseudorandomly generated bits. Many applications will find the method Math.random() simpler to use. Instances of java.util.Random are threadsafe. However, the concurrent use of the same java.util.Random instance across threads may encounter contention and consequent poor performance. Consider instead using ThreadLocalRandom in multithreaded designs. Instances of java.util.Random are not cryptographically secure. Consider instead using SecureRandom to get a cryptographically secure pseudo-random number generator for use by security-sensitive applications.Since:1.0See Also:Serialized FormConstructor SummaryConstructors Constructor and DescriptionRandom()Creates a new random number generator.Random(long seed)Creates a new random number generator using a single long seed.Method SummaryAll Methods Instance Methods Concrete Methods Modifier and TypeMethod and DescriptionDoubleStreamdoubles()Returns an effectively unlimited stream of pseudorandom double values, each between zero (inclusive) and one (exclusive).DoubleStreamdoubles(double randomNumberOrigin, double randomNumberBound)Returns an effectively unlimited stream of pseudorandom double values, each conforming to the given origin (inclusive) and bound (exclusive).DoubleStreamdoubles(long streamSize)Returns a stream producing the given streamSize number of pseudorandom double values, each between zero (inclusive) and one (exclusive).DoubleStreamdoubles(long streamSize, double randomNumberOrigin, double randomNumberBound)Returns a stream producing the given streamSize number of pseudorandom double values, each conforming to the given origin (inclusive) and bound (exclusive).IntStreamints()Returns an effectively unlimited stream of pseudorandom int values.IntStreamints(int randomNumberOrigin, int randomNumberBound)Returns an effectively unlimited stream of pseudorandom int values, each conforming to the given origin (inclusive) and bound (exclusive).IntStreamints(long streamSize)Returns a stream producing the given streamSize number of pseudorandom int values.IntStreamints(long streamSize, int randomNumberOrigin, int randomNumberBound)Returns a stream producing the given streamSize number of pseudorandom int values, each conforming to the given origin (inclusive) and bound (exclusive).LongStreamlongs()Returns an effectively unlimited stream of pseudorandom long values.LongStreamlongs(long streamSize)Returns a stream producing the given streamSize number of pseudorandom long values.LongStreamlongs(long randomNumberOrigin, long randomNumberBound)Returns an effectively unlimited stream of pseudorandom long values, each conforming to the given origin (inclusive) and bound (exclusive).LongStreamlongs(long streamSize, long randomNumberOrigin, long randomNumberBound)Returns a stream producing the given streamSize number of pseudorandom long, each conforming to the given origin (inclusive) and bound (exclusive).protected intnext(int bits)Generates the next pseudorandom number.booleannextBoolean()Returns the next pseudorandom, uniformly distributed boolean value from this random number generator's sequence.voidnextBytes(byte[] bytes)Generates random bytes and places them into a user-supplied byte array.doublenextDouble()Returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator's sequence.floatnextFloat()Returns the next pseudorandom, uniformly distributed float value between 0.0 and 1.0 from this random number generator's sequence.doublenextGaussian()Returns the next pseudorandom, Gaussian ("normally") distributed double value with mean 0.0 and standard deviation 1.0 from this random number generator's sequence.intnextInt()Returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence.intnextInt(int bound)Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.longnextLong()Returns the next pseudorandom, uniformly distributed long value from this random number generator's sequence.voidsetSeed(long seed)Sets the seed of this random number generator using a single long seed.Methods inherited from class java.lang.Objectclone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitConstructor DetailRandompublic Random()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.Randompublic Random(long seed)Creates a new random number generator using a single long seed. The seed is the initial value of the internal state of the pseudorandom number generator which is maintained by method next(int). The invocation new Random(seed) is equivalent to: Random rnd = new Random(); rnd.setSeed(seed);Parameters:seed - the initial seedSee Also:setSeed(long)Method DetailsetSeedpublic void setSeed(long seed)Sets the seed of this random number generator using a single long seed. The general contract of setSeed is that it alters the state of this random number generator object so as to be in exactly the same state as if it had just been created with the argument seed as a seed. The method setSeed is implemented by class Random by atomically updating the seed to (seed ^ 0x5DEECE66DL) & ((1L > (48 - bits)). This is a linear congruential pseudorandom number generator, as defined by D. H. Lehmer and described by Donald E. Knuth in The Art of Computer Programming, Volume 3: Seminumerical Algorithms, section 3.2.1.Parameters:bits - random bitsReturns:the next pseudorandom value from this random number generator's sequenceSince:1.1nextBytespublic void nextBytes(byte[] bytes)Generates random bytes and places them into a user-supplied byte array. The number of random bytes produced is equal to the length of the byte array. The method nextBytes is implemented by class Random as if by: public void nextBytes(byte[] bytes) for (int i = 0; i < bytes.length; ) for (int rnd = nextInt(), n = Math.min(bytes.length - i, 4); n-- > 0; rnd >>= 8) bytes[i++] = (byte)rnd; Parameters:bytes - the byte array to fill with random bytesThrows:NullPointerException - if the byte array is nullSince:1.1nextIntpublic int nextInt()Returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence. The general contract of nextInt is that one int value is pseudorandomly generated and returned. All 232 possible int values are produced with (approximately) equal probability. The method nextInt is implemented by class Random as if by: public int nextInt() return next(32); Returns:the next pseudorandom, uniformly distributed int value from this random number generator's sequencenextIntpublic int nextInt(int bound)Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. The general contract of nextInt is that one int value in the specified range is pseudorandomly generated and returned. All bound possible int values are produced with (approximately) equal probability. The method nextInt(int bound) is implemented by class Random as if by: public int nextInt(int bound) if (bound > 31); int bits, val; do bits = next(31); val = bits % bound; while (bits - val + (bound-1) < 0); return val; The hedge "approximately" is used in the foregoing description only because the next method is only approximately an unbiased source of independently chosen bits. If it were a perfect source of randomly chosen bits, then the algorithm shown would choose int values from the stated range with perfect uniformity. The algorithm is slightly tricky. It rejects values that would result in an uneven distribution (due to the fact that 2^31 is not divisible by n). The probability of a value being rejected depends on n. The worst case is n=2^30+1, for which the probability of a reject is 1/2, and the expected number of iterations before the loop terminates is 2. The algorithm treats the case where n is a power of two specially: it returns the correct number of high-order bits from the underlying pseudo-random number generator. In the absence of special treatment, the correct number of low-order bits would be returned. Linear congruential pseudo-random number generators such as the one implemented by this class are known to have short periods in the sequence of values of their low-order bits. Thus, this special case greatly increases the length of the sequence of values returned by successive calls to this method if n is a small power of two.Parameters:bound - the upper bound (exclusive). Must be positive.Returns:the next pseudorandom, uniformly distributed int value between zero (inclusive) and bound (exclusive) from this random number generator's sequenceThrows:IllegalArgumentException - if bound is not positiveSince:1.2nextLongpublic long nextLong()Returns the next pseudorandom, uniformly distributed long value from this random number generator's sequence. The general contract of nextLong is that one long value is pseudorandomly generated and returned. The method nextLong is implemented by class Random as if by: public long nextLong() { return ((long)next(32)
c80f0f1006