Class GoldenQuasiRandom
- All Implemented Interfaces:
Externalizable,Serializable,RandomGenerator
Useful traits of this generator are that it has exactly one
long of state, that all values are
permitted for that state, and that you can skip(long) the state forwards or backwards in constant time.
It is also extremely fast, though it shouldn't be compared to pseudo-random number generators. It implements
nextGaussian() and its overload specially; these methods advance the state differently and don't return
quasi-random output (it's much closer to pseudo-random, and is similar to DistinctRandom's approach). The
Gaussian methods needed this treatment because anything that requested multiple Gaussian-distributed variables each
time it produced one output (such as a Chi or Beta distribution) would have extremely noticeable, severe artifacts.
Because there's always a strong separation between subsequent results of EnhancedRandom.nextDouble(), that made the
Gaussian doubles have large gaps in their output range, because some combinations were impossible.
This class is an
EnhancedRandom from juniper and is also a JDK Random as a result.
This doesn't randomize the seed when given one with
setSeed(long), and it doesn't do anything else to
randomize the output, so sequential seeds will produce extremely similar sequences. You can randomize sequential
seeds using something like Hasher.randomize3(long), if you want random starting points.
This implements all methods from
EnhancedRandom, including the optional skip(long) and
previousLong() methods.- See Also:
-
Nested Class Summary
Nested classes/interfaces inherited from interface java.util.random.RandomGenerator
RandomGenerator.ArbitrarilyJumpableGenerator, RandomGenerator.JumpableGenerator, RandomGenerator.LeapableGenerator, RandomGenerator.SplittableGenerator, RandomGenerator.StreamableGenerator -
Field Summary
Fields -
Constructor Summary
ConstructorsConstructorDescriptionCreates a new GoldenQuasiRandom with a random state.GoldenQuasiRandom(long state) Creates a new GoldenQuasiRandom with the given state; alllongvalues are permitted. -
Method Summary
Modifier and TypeMethodDescriptioncopy()Creates a new EnhancedRandom with identical states to this one, so if the same EnhancedRandom methods are called on this object and its copy (in the same order), the same outputs will be produced.boolean2 to the 64.longgetSelectedState(int selection) Gets the only state, which can be any long value.longgetState()Gets the current state; it's already public, but I guess this could still be useful.intThis has one long state.getTag()Gets the tag used to identify this type of EnhancedRandom, as a String.intnext(int bits) Generates the next pseudorandom number with a specific maximum size in bits (not a max number).doubleGets a random double between 0.0 and 1.0, exclusive at both ends; this method is also more uniform thanEnhancedRandom.nextDouble()if you use the bit-patterns of the returned doubles.floatGets a random float between 0.0 and 1.0, exclusive at both ends.doubleGets a random double that may be positive or negative, but cannot be 0, and always has a magnitude less than 1.floatGets a random float that may be positive or negative, but cannot be 0, and always has a magnitude less than 1.doubleReturns the next pseudorandom, Gaussian ("normally") distributeddoublevalue with mean0.0and standard deviation1.0from this random number generator's sequence.intnextInt()Returns the next pseudorandom, uniformly distributedintvalue from this random number generator's sequence.intnextInt(int bound) Returns a pseudorandom, uniformly distributedintvalue between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.longnextLong()Returns the next pseudorandom, uniformly distributedlongvalue from this random number generator's sequence.intnextSignedInt(int outerBound) Returns a pseudorandom, uniformly distributedintvalue between an inner bound of 0 (inclusive) and the specifiedouterBound(exclusive).longOptional; moves the state to its previous value and returns the previous long that would have been produced byEnhancedRandom.nextLong().voidsetSeed(long seed) Sets the only state, which can be given any long value; this seed value will not be altered.voidsetSelectedState(int selection, long value) Sets the only state, which can be given any long value.voidsetState(long state) Sets each state variable to the givenstate.longskip(long advance) Skips the state forward or backwards by the givenadvance, then returns the result ofnextLong()at the same point in the sequence.toString()Methods inherited from class com.github.tommyettinger.random.EnhancedRandom
appendSerialized, appendSerialized, areEqual, fixGamma, fixGamma, lcm, mainlyGeneratesInt, maxDoubleOf, maxFloatOf, maxIntOf, maxLongOf, minDoubleOf, minFloatOf, minIntOf, minLongOf, nextBoolean, nextBoolean, nextBytes, nextDouble, nextDouble, nextDouble, nextExclusiveDouble, nextExclusiveDouble, nextExclusiveDoubleEquidistant, nextExclusiveFloat, nextExclusiveFloat, nextExclusiveFloatEquidistant, nextExponential, nextFloat, nextFloat, nextFloat, nextGaussian, nextInclusiveDouble, nextInclusiveDouble, nextInclusiveDouble, nextInclusiveFloat, nextInclusiveFloat, nextInclusiveFloat, nextInt, nextLong, nextLong, nextSign, nextSignedInt, nextSignedLong, nextSignedLong, nextTriangular, nextTriangular, nextTriangular, nextTriangular, nextUnsignedInt, previousInt, probit, randomElement, randomElement, rateGamma, readExternal, seedFromMath, setState, setState, setState, setState, setState, setState, setWith, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, stringDeserialize, stringDeserialize, stringSerialize, stringSerialize, writeExternalMethods inherited from class java.util.Random
doubles, doubles, doubles, doubles, ints, ints, ints, ints, longs, longs, longs, longsMethods inherited from class java.lang.Object
clone, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitMethods inherited from interface java.util.random.RandomGenerator
isDeprecated
-
Field Details
-
state
public long stateThe only long state variable; can be anylong.
-
-
Constructor Details
-
GoldenQuasiRandom
public GoldenQuasiRandom()Creates a new GoldenQuasiRandom with a random state. -
GoldenQuasiRandom
public GoldenQuasiRandom(long state) Creates a new GoldenQuasiRandom with the given state; alllongvalues are permitted.- Parameters:
state- anylongvalue
-
-
Method Details
-
getTag
Description copied from class:EnhancedRandomGets the tag used to identify this type of EnhancedRandom, as a String. This tag should be unique, and for uniformity purposes, all tags used in this library are 4 characters long. User-defined tags should have a different length.- Specified by:
getTagin classEnhancedRandom- Returns:
- a unique String identifier for this type of EnhancedRandom; usually 4 chars long.
-
getMinimumPeriod
2 to the 64.- Overrides:
getMinimumPeriodin classEnhancedRandom- Returns:
- 2 to the 64
-
getStateCount
public int getStateCount()This has one long state.- Overrides:
getStateCountin classEnhancedRandom- Returns:
- 1 (one)
-
getSelectedState
public long getSelectedState(int selection) Gets the only state, which can be any long value.- Overrides:
getSelectedStatein classEnhancedRandom- Parameters:
selection- ignored; this always returns the same, only state- Returns:
- the only state's exact value
-
setSelectedState
public void setSelectedState(int selection, long value) Sets the only state, which can be given any long value. The selection can be anything and is ignored.- Overrides:
setSelectedStatein classEnhancedRandom- Parameters:
selection- ignored; this always sets the same, only statevalue- the exact value to use for the state; all longs are valid
-
setSeed
public void setSeed(long seed) Sets the only state, which can be given any long value; this seed value will not be altered. Equivalent tosetSelectedState(int, long)with any selection andseedpassed as thevalue.- Specified by:
setSeedin classEnhancedRandom- Parameters:
seed- the exact value to use for the state; all longs are valid
-
getState
public long getState()Gets the current state; it's already public, but I guess this could still be useful. The state can be anylong.- Returns:
- the current state, as a long
-
setState
public void setState(long state) Sets each state variable to the givenstate. This implementation simply sets the one state variable tostate.- Overrides:
setStatein classEnhancedRandom- Parameters:
state- the long value to use for the state variable
-
nextLong
public long nextLong()Description copied from class:EnhancedRandomReturns the next pseudorandom, uniformly distributedlongvalue from this random number generator's sequence. The general contract ofnextLongis that onelongvalue is pseudorandomly generated and returned.
The only methods that need to be implemented by this interface are this andEnhancedRandom.copy(), though other methods can be implemented as appropriate for generators that, for instance, natively produce ints rather than longs.- Specified by:
nextLongin interfaceRandomGenerator- Specified by:
nextLongin classEnhancedRandom- Returns:
- the next pseudorandom, uniformly distributed
longvalue from this random number generator's sequence
-
skip
public long skip(long advance) Skips the state forward or backwards by the givenadvance, then returns the result ofnextLong()at the same point in the sequence. If advance is 1, this is equivalent to nextLong(). If advance is 0, this returns the samelongas the previous call to the generator (if it called nextLong()), and doesn't change the state. If advance is -1, this moves the state backwards and produces thelongbefore the last one generated by nextLong(). More positive numbers move the state further ahead, and more negative numbers move the state further behind; all of these take constant time.- Overrides:
skipin classEnhancedRandom- Parameters:
advance- how many steps to advance the state before generating along- Returns:
- a random
longby the same algorithm asnextLong(), using the appropriately-advanced state
-
previousLong
public long previousLong()Description copied from class:EnhancedRandomOptional; moves the state to its previous value and returns the previous long that would have been produced byEnhancedRandom.nextLong(). This can be equivalent to callingEnhancedRandom.skip(long)with -1L, but not always; many generators can't efficiently skip long distances, but can step back by one value.
Generators that natively generateintresults typically producelongvalues by generating an int for the high 32 bits and an int for the low 32 bits. When producing the previous long, the order the high and low bits are generated, such as byEnhancedRandom.previousInt(), should be reversed. Generators that natively producelongvalues usually don't need to implementEnhancedRandom.previousInt(), but those that produceintusually should implement it, and may optionally call previousInt() twice in this method.
If you know how to implement the reverse of a particular random number generator, it is recommended you do so here, rather than rely on skip(). This isn't always easy, but should always be possible for any decent PRNG (some historical PRNGs, such as the Middle-Square PRNG, cannot be reversed at all). If a generator cannot be reversed because multiple initial states can transition to the same subsequent state, it is known to have statistical problems that are not necessarily present in a generator that matches one initial state to one subsequent state.
The public implementation callsEnhancedRandom.skip(long)with -1L, and if skip() has not been implemented differently, then it will throw an UnsupportedOperationException.- Overrides:
previousLongin classEnhancedRandom- Returns:
- the previous number this would have produced with
EnhancedRandom.nextLong()
-
next
public int next(int bits) Description copied from class:EnhancedRandomGenerates the next pseudorandom number with a specific maximum size in bits (not a max number). If you want to get a random number in a range, you should usually useEnhancedRandom.nextInt(int)instead. For some specific cases, this method is more efficient and less biased thanEnhancedRandom.nextInt(int). Forbitsvalues between 1 and 30, this should be similar in effect tonextInt(1 << bits); though it won't typically produce the same values, they will have the correct range. Ifbitsis 31, this can return any non-negativeint; note thatnextInt(1 << 31)won't behave this way because1 << 31is negative. Ifbitsis 32 (or 0), this can return anyint.The general contract of
nextis that it returns anintvalue and if the argumentbitsis between1and32(inclusive), then that many low-order bits of the returned value will be (approximately) independently chosen bit values, each of which is (approximately) equally likely to be0or1.Note that you can give this values for
bitsthat are outside its expected range of 1 to 32, but the value used, as long as bits is positive, will effectively bebits % 32. As stated before, a value of 0 for bits is the same as a value of 32.- Overrides:
nextin classEnhancedRandom- Parameters:
bits- the amount of random bits to request, from 1 to 32- Returns:
- the next pseudorandom value from this random number generator's sequence
-
nextInt
public int nextInt()Description copied from class:EnhancedRandomReturns the next pseudorandom, uniformly distributedintvalue from this random number generator's sequence. The general contract ofnextIntis that oneintvalue is pseudorandomly generated and returned. All 232 possibleintvalues are produced with (approximately) equal probability.- Specified by:
nextIntin interfaceRandomGenerator- Overrides:
nextIntin classEnhancedRandom- Returns:
- the next pseudorandom, uniformly distributed
intvalue from this random number generator's sequence
-
nextInt
public int nextInt(int bound) Description copied from class:EnhancedRandomReturns a pseudorandom, uniformly distributedintvalue between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. The general contract ofnextIntis that oneintvalue in the specified range is pseudorandomly generated and returned. Allboundpossibleintvalues are produced with (approximately) equal probability.
This method clamps bound to be at least 0; it never returns a negative int.
It should be mentioned that the technique this uses has some bias, depending onbound, but it typically isn't measurable without specifically looking for it. Using the method this does allows this method to always advance the state by one step, instead of a varying and unpredictable amount with the more typical ways of rejection-sampling random numbers and only using numbers that can produce an int within the bound without bias. See M.E. O'Neill's blog about random numbers for discussion of alternative, unbiased methods.- Specified by:
nextIntin interfaceRandomGenerator- Overrides:
nextIntin classEnhancedRandom- Parameters:
bound- the upper bound (exclusive). If negative or 0, this always returns 0.- Returns:
- the next pseudorandom, uniformly distributed
intvalue between zero (inclusive) andbound(exclusive) from this random number generator's sequence
-
nextSignedInt
public int nextSignedInt(int outerBound) Description copied from class:EnhancedRandomReturns a pseudorandom, uniformly distributedintvalue between an inner bound of 0 (inclusive) and the specifiedouterBound(exclusive). This is meant for cases where the outer bound may be negative, especially if the bound is unknown or may be user-specified. A negative outer bound is used as the lower bound; a positive outer bound is used as the upper bound. An outer bound of -1, 0, or 1 will always return 0, keeping the bound exclusive (except for outer bound 0). This method is slightly slower thanEnhancedRandom.nextInt(int).- Overrides:
nextSignedIntin classEnhancedRandom- Parameters:
outerBound- the outer exclusive bound; may be any int value, allowing negative- Returns:
- a pseudorandom int between 0 (inclusive) and outerBound (exclusive)
- See Also:
-
nextExclusiveDouble
public double nextExclusiveDouble()Description copied from class:EnhancedRandomGets a random double between 0.0 and 1.0, exclusive at both ends; this method is also more uniform thanEnhancedRandom.nextDouble()if you use the bit-patterns of the returned doubles. This is a simplified version of this algorithm by Allen Downey. This can return double values between 2.710505431213761E-20 and 0.9999999999999999, or 0x1.0p-65 and 0x1.fffffffffffffp-1 in hex notation. It cannot return 0 or 1. Some cases can preferEnhancedRandom.nextExclusiveDoubleEquidistant(), which is implemented more traditionally but may have slower performance. This method can also return doubles that are extremely close to 0, but can't return doubles that are as close to 1, due to how floating-point numbers work. However, nextExclusiveDoubleEquidistant() can return only a minimum value that is as distant from 0 as its maximum value is distant from 1.
To compare, nextDouble() and nextExclusiveDoubleEquidistant() are less likely to produce a "1" bit for their lowest 5 bits of mantissa/significand (the least significant bits numerically, but potentially important for some uses), with the least significant bit produced half as often as the most significant bit in the mantissa. As for this method, it has approximately the same likelihood of producing a "1" bit for any position in the mantissa.
The implementation may have different performance characteristics thanEnhancedRandom.nextDouble(), because this doesn't perform any floating-point multiplication or division, and instead assembles bits obtained by one call toEnhancedRandom.nextLong(). This usesBitConversion.longBitsToDouble(long)andBitConversion.countLeadingZeros(long), both of which typically have optimized intrinsics on HotSpot, and this is branchless and loopless, unlike the original algorithm by Allen Downey. When compared withEnhancedRandom.nextExclusiveDoubleEquidistant(), this method performs better on at least HotSpot JVMs. On GraalVM 17, this is over twice as fast as nextExclusiveDoubleEquidistant().- Overrides:
nextExclusiveDoublein classEnhancedRandom- Returns:
- a random uniform double between 2.710505431213761E-20 and 0.9999999999999999 (both inclusive)
-
nextExclusiveSignedDouble
public double nextExclusiveSignedDouble()Description copied from class:EnhancedRandomGets a random double that may be positive or negative, but cannot be 0, and always has a magnitude less than 1.
This is a modified version of this algorithm by Allen Downey. This version can return double values between -0.9999999999999999 and -5.421010862427522E-20, as well as between 5.421010862427522E-20 and 0.9999999999999999, or -0x1.fffffffffffffp-1 to -0x1.0p-64 as well as between 0x1.0p-64 and 0x1.fffffffffffffp-1 in hex notation. It cannot return -1, 0 or 1. It has much more uniform bit distribution across its mantissa/significand bits thanRandom.nextDouble(), especially when the result of nextDouble() is expanded to the -1.0 to 1.0 range (such as with2.0 * (nextDouble() - 0.5)). Where that code usingEnhancedRandom.nextDouble()is unable to produce a "1" bit for its lowest bit of mantissa (the least significant bits numerically, but potentially important for some uses), this has approximately the same likelihood of producing a "1" bit for any positions in the mantissa, and also equal odds for the sign bit.
Some useful properties here are that this produces a negative result exactly as often as the underlying generator produces a negative result withEnhancedRandom.nextLong(), and the least-significant bits that the underlying generator produces withEnhancedRandom.nextLong()are also the least-significant in magnitude here. This could be used with lower-quality randomness, like a linear congruential generator, and the flaws those have with their low-order bits would barely affect floating-point results here. This generator also produces results that are symmetrical around 0.0, with every possible positive number having a possible negative number of equal magnitude, if the underlying generator is at least 1-dimensionally equidistributed. Note that generators such asXoroshiro128StarStarRandomandXoshiro256StarStarRandomcannot return 0L fromEnhancedRandom.nextLong()as frequently as other results, so this is not (technically) true of those. Those generators (and other LFSR-type generators) will produce 5.421010862427522E-20 less frequently than -5.421010862427522E-20 .- Overrides:
nextExclusiveSignedDoublein classEnhancedRandom- Returns:
- a random uniform double between -1 and 1 with a tiny hole around 0 (all exclusive)
-
nextExclusiveFloat
public float nextExclusiveFloat()Description copied from class:EnhancedRandomGets a random float between 0.0 and 1.0, exclusive at both ends. This method is also more uniform thanEnhancedRandom.nextFloat()if you use the bit-patterns of the returned floats. This is a simplified version of this algorithm by Allen Downey. This version can return float values between 2.7105054E-20 to 0.99999994, or 0x1.0p-65 to 0x1.fffffep-1 in hex notation. It cannot return 0 or 1. To compare, nextFloat() is less likely to produce a "1" bit for its lowest 5 bits of mantissa/significand (the least significant bits numerically, but potentially important for some uses), with the least significant bit produced half as often as the most significant bit in the mantissa. As for this method, it has approximately the same likelihood of producing a "1" bit for any position in the mantissa.
The implementation may have different performance characteristics thanEnhancedRandom.nextFloat(), because this doesn't perform any floating-point multiplication or division, and instead assembles bits obtained by one call toEnhancedRandom.nextLong(). This usesBitConversion.intBitsToFloat(int)andBitConversion.countLeadingZeros(long), both of which typically have optimized intrinsics on HotSpot, and this is branchless and loopless, unlike the original algorithm by Allen Downey. When compared withEnhancedRandom.nextExclusiveFloatEquidistant(), this method performs better on at least HotSpot JVMs. On GraalVM 17, this is over twice as fast as nextExclusiveFloatEquidistant().- Overrides:
nextExclusiveFloatin classEnhancedRandom- Returns:
- a random uniform float between 0 and 1 (both exclusive)
-
nextExclusiveSignedFloat
public float nextExclusiveSignedFloat()Description copied from class:EnhancedRandomGets a random float that may be positive or negative, but cannot be 0, and always has a magnitude less than 1.
This is a modified version of this algorithm by Allen Downey. This version can return float values between -0.99999994 and -5.421011E-20, as well as between 5.421011E-20 and 0.99999994, or -0x1.fffffep-1 to -0x1.0p-64 as well as between 0x1.0p-64 and 0x1.fffffep-1 in hex notation. It cannot return -1, 0 or 1. It has much more uniform bit distribution across its mantissa/significand bits thanRandom.nextFloat(), especially when the result of nextFloat() is expanded to the -1.0 to 1.0 range (such as with2.0 * (nextFloat() - 0.5)). Where the given example code is unable to produce a "1" bit for its lowest bit of mantissa (the least significant bits numerically, but potentially important for some uses), this has approximately the same likelihood of producing a "1" bit for any positions in the mantissa, and also equal odds for the sign bit.
Some useful properties here are that this produces a negative result exactly as often as the underlying generator produces a negative result withEnhancedRandom.nextLong(), and the least-significant bits that the underlying generator produces withEnhancedRandom.nextLong()are also the least-significant in magnitude here. This could be used with lower-quality randomness, like a linear congruential generator, and the flaws those have with their low-order bits would barely affect floating-point results here. This generator also produces results that are symmetrical around 0.0, with every possible positive number having a possible negative number of equal magnitude, if the underlying generator is at least 1-dimensionally equidistributed. Note that generators such asXoroshiro128StarStarRandomandXoshiro256StarStarRandomcannot return 0L fromEnhancedRandom.nextLong()as frequently as other results, so this is not (technically) true of those. Those generators (and other LFSR-type generators) will produce 5.421011E-20 less frequently than -5.421011E-20 .- Overrides:
nextExclusiveSignedFloatin classEnhancedRandom- Returns:
- a random uniform float between -1 and 1 with a tiny hole around 0 (all exclusive)
-
nextGaussian
public double nextGaussian()Description copied from class:EnhancedRandomReturns the next pseudorandom, Gaussian ("normally") distributeddoublevalue with mean0.0and standard deviation1.0from this random number generator's sequence.The general contract of
nextGaussianis that onedoublevalue, chosen from (approximately) the usual normal distribution with mean0.0and standard deviation1.0, is pseudorandomly generated and returned.This does not use a rough approximation, which is a departure from earlier versions; instead, it uses the Ziggurat method, which produces high-quality variables very quickly. Like earlier versions that used probit() or a bit-counting approximation, this requests exactly one long from the generator's sequence (using
EnhancedRandom.nextLong()). This makes it different from code like java.util.Random's nextGaussian() method, which can (rarely) fetch a higher number of random doubles.The implementation here was ported from code by Olaf Berstein, based on a paper by Jorgen A. Doornik and some steps from a paper by George Marsaglia.
Distributorhas more information, for the curious.- Specified by:
nextGaussianin interfaceRandomGenerator- Overrides:
nextGaussianin classEnhancedRandom- Returns:
- the next pseudorandom, Gaussian ("normally") distributed
doublevalue with mean0.0and standard deviation1.0from this random number generator's sequence
-
copy
Description copied from class:EnhancedRandomCreates a new EnhancedRandom with identical states to this one, so if the same EnhancedRandom methods are called on this object and its copy (in the same order), the same outputs will be produced. This is not guaranteed to copy the inherited state of any parent class, so if you call methods that are only implemented by a superclass (likeRandom) and not this one, the results may differ.- Specified by:
copyin classEnhancedRandom- Returns:
- a deep copy of this EnhancedRandom.
-
equals
-
toString
-