You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
api-approvedAPI was approved in API review, it can be implementedarea-System.Numericsin-prThere is an active PR which will close this issue when it is merged
Now that we have the generic math interfaces, we should be able to write a method for generating a random value that can work with any T where T implements the appropriate interface.
The range used for NextDouble is 0.0 to 1.0; for a floating-point API, we'd presumably want to map to the same range?
Same for NextSingle() so I think so.
It might be interesting to have a quick look at what random methods other stacks expose.
Humbly I leave here my (not well written) random utilities I use when I need to seed to test something. As example of some useful methods or generics could be integrated
publicstaticclassRandomExtensions{publicstaticboolCoinToss(thisRandomrng){returnCoinToss(rng,.5);}publicstaticboolCoinToss(thisRandomrng,doublezeroWeight){returnrng.NextDouble()>=zeroWeight;}publicstaticbyteNextByte(thisRandomrng){return(byte)rng.Next(byte.MinValue,byte.MaxValue+1);}publicstaticbyteNextByte(thisRandomrng,bytemin,bytemax){return(byte)rng.Next(min,max);}publicstaticsbyteNextSbyte(thisRandomrng){return(sbyte)rng.Next(sbyte.MinValue,sbyte.MaxValue+1);}publicstaticsbyteNextSbyte(thisRandomrng,sbytemin,sbytemax){return(sbyte)rng.Next(min,max);}publicstaticDateTimeNextDateTime(thisRandomrng){returnNextDateTime(rng,DateTime.MinValue,DateTime.MaxValue);}publicstaticDateTimeNextDateTime(thisRandomrng,DateTimemaxValue){returnNextDateTime(rng,DateTime.MinValue,maxValue);}publicstaticDateTimeNextDateTime(thisRandomrng,DateTimeminValue,DateTimemaxValue){if(minValue>=maxValue)thrownewArgumentOutOfRangeException(nameof(minValue));varnextLong=rng.NextLong(minValue.Ticks,maxValue.Ticks);returnnewDateTime(nextLong);}publicstaticDateOnlyNextDate(thisRandomrng){returnNextDate(rng,DateOnly.MinValue,DateOnly.MaxValue);}publicstaticDateOnlyNextDate(thisRandomrng,DateOnlymaxValue){returnNextDate(rng,DateOnly.MinValue,maxValue);}publicstaticDateOnlyNextDate(thisRandomrng,DateOnlyminValue,DateOnlymaxValue){if(minValue>=maxValue)thrownewArgumentOutOfRangeException(nameof(minValue));varnextDay=rng.Next(minValue.DayNumber,maxValue.DayNumber);returnDateOnly.FromDayNumber(nextDay);}publicstaticTimeOnlyNextTime(thisRandomrng){returnNextTime(rng,TimeOnly.MinValue,TimeOnly.MaxValue);}publicstaticTimeOnlyNextTime(thisRandomrng,TimeOnlymaxValue){returnNextTime(rng,TimeOnly.MinValue,maxValue);}publicstaticTimeOnlyNextTime(thisRandomrng,TimeOnlyminValue,TimeOnlymaxValue){if(minValue>=maxValue)thrownewArgumentOutOfRangeException(nameof(minValue));varnextLong=rng.NextLong(minValue.Ticks,maxValue.Ticks);returnnewTimeOnly(nextLong);}publicstaticdoubleNextDouble(thisRandomrng,doubleminValue,doublemaxValue){returnminValue+rng.NextDouble()*(maxValue-minValue);}publicstaticlongNextLong(thisRandomrng){returnNextLong(rng,0,long.MaxValue);}publicstaticlongNextLong(thisRandomrng,longmaxValue){returnNextLong(rng,0,maxValue);}publicstaticlongNextLong(thisRandomrng,longminValue,longmaxValue){if(minValue>=maxValue)thrownewArgumentOutOfRangeException(nameof(minValue));//Working with ulong so that modulo works correctly with values > long.MaxValuevaruRange=(ulong)(maxValue-minValue);//Prevent a modolo bias; see https://stackoverflow.com/a/10984975/238419//for more information.//In the worst case, the expected number of calls is 2 (though usually it's//much closer to 1) so this loop doesn't really hurt performance at all.ulongulongRand;varbuf=(stackallocbyte[8]);do{rng.NextBytes(buf);ulongRand=(ulong)BitConverter.ToInt64(buf);}while(ulongRand>ulong.MaxValue-((ulong.MaxValue%uRange)+1)%uRange);return(long)(ulongRand%uRange)+minValue;}publicstaticcharNextChar(thisRandomrng){returnNextChar(rng,char.MinValue,char.MaxValue);}publicstaticcharNextChar(thisRandomrng,charmaxValue){returnNextChar(rng,char.MinValue,maxValue);}publicstaticcharNextChar(thisRandomrng,charminValue,charmaxValue){if(minValue>=maxValue)thrownewArgumentOutOfRangeException(nameof(minValue));intmin=minValue;intmax=maxValue;return(char)rng.Next(min,max);}publicstaticstringNextString(thisRandomrng,intlength){returnNextString(rng,length,char.MinValue,char.MaxValue);}publicstaticstringNextString(thisRandomrng,intlength,charmaxValue){returnNextString(rng,length,char.MinValue,maxValue);}publicstaticstringNextString(thisRandomrng,intlength,charminValue,charmaxValue){if(length<0)thrownewArgumentOutOfRangeException(nameof(length));varstrSpan=(stackallocchar[length]);for(inti=0;i<length;i++){strSpan[i]=NextChar(rng,minValue,maxValue);}returnstrSpan.ToString();}}
In the existing APIs, minValue is inclusive and maxValue is exclusive. This is using the same naming as the existing overloads and would have the same semantics as the existing overloads.
because Next<T>(T.MinValue, T.MaxValue) will not be the same as Next<T>()
also Next<T>(0, T.MaxValue + 1) will not be possible (assuming T is a signed variant)... if the goal is to have any value of the positive range (of a signed T variant)
I'm not against it, but it has to be clearly stated, I fell into that pitfall many times. The documentation mentions it for the current int implementation in a small remark. For example Next<byte>() can never return 255.
I would on a personal note as this is a new implementation without backward compatibility ...
have Next<T>() return the full range of T
have Next<T>(T minInclusive, T maxInclusive) return a complete range -- or maxExclusive but have the parameter properly named -- problem with exclusive is still no full positive range possible
and when T is a floating point number default to T.Zero and T.One (inclusive)
if default Next<float>() would not include 1 then the random value is not usable for the scenarios I use random float numbers.
Oh, I forgot to mention, it is easy to turn inclusive to exclusive by subtracting 1 or Epsilon, but it is not possible to do the opposite, as T.MaxValue is the maximum value and nothing can be bigger.
raytracing, (audio) signal processing, field density, math, geometry, anything that is too complex to completely calculate... you use a randomization of a normalized set (so 0 to 1) and then calculate until you have enough result values... as the calculation will theoretically go on forever... if the 1 is missing as a random value, one "edge" will be "not sharp"
If you have a large input set, then it doesn't make a difference as by rounding you hit the edge, but sometimes you have a 3 dimensional set or a 4 dimensional set with a very "thin" dimension, for example depth or color/hue (4th dimension). Or you have a reduced data set and the last thing you want is to add a special randomizer for such special cases.
Normalization is usually done with a range of 0 to 1 inclusive. Or -1 to +1 inclusive. The left x-coordinate is 0, the right x-coordinate is 1. Or you have a line from A to B and use a random number to find any point between A and B. But you want A and B both included. A line segment between 2 points includes both points. Normalized, to find A you use 0 and to find B you use 1. In float-color (0,0,0) is Black and (1,1,1) is White, (0.5,0.5,0.5) is Gray etc. The 1 is always part of the set.
Reacted by Tanner Gooding, Dan Moseley, Tim Cassell, GSPP and Thorsten Sommer
I don't think having the same random API for all numeric types is a good idea. Integer numbers and floating-point numbers have different behaviors and expectations. Single generic API for all of them would have very weird behavior. The very core of RNG is producing sequence of uniformly distributed byte values, other methods produce values of specific types from these byte sequences. With that in mind we can look at differences in numeric types:
Binary integers (from System.Byte to System.Int64, signed and unsigned) have values that are uniformly distributed. Every interval also has uniformly distributed values. So, producing a binary integer from byte sequence is almost as easy as filling the memory span with these bytes (there are tricks to support Next(min, max), more on that later). When users call Random.Next<TBinaryInteger>(min, max), they expect to receive uniformly distributed values.
IEEE754 floating-point numbers (System.Half, System.Single, System.Double) have values that are not uniformly distributed. Some intervals have uniformly distributed numbers, some haven't - it depends on whether only mantissa is changing, or there's a change in value of exponent as well. If we simply fill a memory span with random bytes we won't get a uniform distribution, we'll get a distribution with logarithmic density, which behaves very counter-intuitively. There is a way to produce uniformly distributed values in the interval [0.0; 1.0) utilizing dyadic rationals and the specific size of mantissa, which is used in current implementation. Maybe we can define Next(max) and Next(min, max) for floating point numbers from Next(0, 1) via linear transformation, but I'm not sure if that's a good idea - precision loss can skew the distribution.
Non-IEEE754 floating-point numbers (System.Decimal) is its own can of worms, I can't say a lot about it, maybe have specific API for decimals? With a way to pass a specific required precision.
Other new numeric types - Here be dragons! What should Random.Next<BigInteger>() produce? Should Random.Next<Complex>() produce values from full Complex plane or from unit circle?
Proposed API shape
publicclassRandom{publicTNext<T>()whereT:IBinaryInteger<T>;// produces values from [T.Zero;T.MaxValue)publicTNext<T>(TmaxValue)whereT:IBinaryInteger<T>;// produces values from [T.Zero;maxValue)publicTNext<T>(TminValue,TmaxValue)whereT:IBinaryInteger<T>;// produces values from [minValue;maxValue)publicTNextFloat<T>()whereT:IBinaryFloatingPointIeee754<T>// produces values from [0.0;1.0), can't have the same name :(}
Basically, Next<T> for binary integers should produce values in the same range as existing methods, i.e., Random.Next<System.Int32>() should behave the same way Random.Next() behaves now.
Other questions
To implement Next(min, max) for binary integers current implementation uses the range hit test, utilizing Log2Ceiling. Do we have Log2Ceiling for every binary integer type? Or Log2 + PopCount?
To produce [0.0; 1.0) uniform distribution current implementation uses dyadic rationals, utilizing type-specific bit-twiddling. Do we have required constants to implement this bit-twiddling in a generic way?
P.S. Maybe it is useful to provide raw span filling method in API, e.g.:
Before adding newer and newer members to Random please consider the API suggestion I proposed in #60549.
ℹ️ Background Info: The problem is that since C# 2.0 adding new virtual members to Random is a breaking change for derived Random classes because until the creator of the derived class can release a new version of their library the non-overridden new methods will fall back to the legacy Random behavior.
Breaking Issue Example:
The last good example is the introduction of NextInt64 and NextSingle methods. I have a SecureRandom class (amongothers). When .NET 6 was released with the new NextInt64 overloads, and before I could release a new version with the new overloads (or even after, if someone targeted .NET 6 without upgrading my libraries), SecureRandom.NextInt64 failed to return cryptographically secure results.
Even worse (though the issue stands also without this addendum), I actually have a lot of extension methods, for Random, including some NextInt64 overloads that returned secure results before .NET 6 but when Random.NextInt64 has been introduced, it was not the case anymore until I upgraded my libraries.
Possible Solutions:
A. Instead of new Random members please introduce new extension methods that rely on the already existing members of any Random implementation (eg. NextBytes). Just like @DrkWzrd, I also offer my RandomExtensions for any possible help/inspiration. Here is a living online example as well.
B. As I proposed in #60549, make it possible for a derived implementation to call a protected base constructor that uses an implementation where all virtual members rely on the Sample method as it was in C# 1.x. This not just prevents unnecessary seed initialization in base but also makes the possible new members forward compatible. The non-overridden members will maybe just be a little less optimized until the library is upgraded but will not fall back to the legacy implementation. I actually even prepared a pull request, in which I followed @GrabYourPitchforks' API review comments, but then unfortunately @stephentoub thought this API was not necessary after all. But now that we face new Random methods again and the same issues can be expected I kindly ask you to reconsider this statement.
Disclaimer:
This API proposal does not indicate the new Next<T> methods as virtual ones. If they are really non-virtual, then maybe my concerns are not that relevant in this particular case. Still, it would be really helpful to consider my proposal as it addresses the unnecessary allocations issue as well.
Correction: I remembered incorrectly: The non-derived compatible implementation of the new NextInt64 method falled back to use multiple Next caused only a performance issue for my SecureRandom class but did not affect security. Meaning, my proposed API is no longer needed to implemented before this proposal. It would be only a solution for the unnecessary allocations and slow instantiation, which an independent issue from the new virtual methods. I apologize for creating an unnecessary noise in this issue.
because until the creator of the derived class can release a new version of their library the non-overridden new method will fall back to the legacy Random behavior.
Any new virtuals that are added delegate to an existing abstract/virtual on the type. In the case of the NextInt64 you mentioned, for example, it would delegate to the existing virtual Next(int), calling a derived type's implementation if it existed. So I'm not sure what you mean about it falling back to legacy behavior.
We have also not historically considered adding new virtual members to be a breaking change. That is exactly how we have to version types (otherwise we'd end up with RandomEx, RandomV5, etc) and we have nearly always reserved the right to extend our types with additional functionality where appropriate.
I feel like I tried something like this from the "batched random" proposal (it ended up with lots of type overloads, and the API Review feedback was "try to make it generic"), and the problem is that IBinaryInteger just says that the value is importable/exportable and it's based on powers of two. It makes no guarantee that the bit pattern of a number that can convert to/from an Int32 value of 2 looks similar to an Int32 with a value of 4.
e.g. imagine an 8-bit number that stores the value of the index into a lookup table for randomized values 0..255 (this is me making a "stop trying to think of an esoteric math function and just say 'mapping table'" timebox limiter), but the math functions all work on the mapped-value rather than the index value.
So, Next(0b0000_0010 (113), 0b0000_0001 (212)) has very unclear behaviors. From a bitwise perspective, max is less than min, but from a value perspective it's bigger, but the only way that I can think of to generate things by flipping bits is (max2 = max - min) and random 0..max2, based on the bit represenation of max2. But that, for my IBinaryInteger here, makes no sense.
Now, we can always document "this is what it does, if your number type does numbers differently than Int32/UInt32, well, sorry, it's gibberish..." but I didn't feel like that would fly in a System.Security namespace. Maybe we're more relaxed for System.Random.
I feel like I tried something like this from the "batched random" proposal (it ended up with lots of type overloads, and the API Review feedback was "try to make it generic"), and the problem is that IBinaryInteger just says that the value is importable/exportable and it's based on powers of two. It makes no guarantee that the bit pattern of a number that can convert to/from an Int32 value of 2 looks similar to an Int32 with a value of 4.
IBinaryInteger<TSelf>.ReadLittleEndian is not documented as importing the internal format of the number, but is currently documented as always importing a little endian twos complement number. This would imply (not documented!) that the WriteLittleEndian must output in that format, otherwise a round trip would change the number. Random certainly can handle making buffers in that format between two values for importing. So either the documentation for that method is wrong, or this should work.
However, if the documentation is correct, then this does mean that the interface does not support exporting the number its its native format, which means that if we had a type documented to be stored in some other format like ones compliment or signed magnitude, then for example Toub's IBinaryInteger<TSelf>.ReverseBits proposal (#125879)'s DIM would reverse bits in the two's complement representation of an arbitrary IBinaryInteger, not its documented encoding, since the DIM literally would have no way of doing that.
Random certainly can handle making buffers in that format between two values for importing.
Yeah, random can make a twos-complement binary representation, but it can't know that the value imported by 0b0010 is necessarily less than the value imported by 0b0100. (Maybe somewhere we have that as an explicit expectation, but I don't know that we assert that x > y implies T.CreateChecked(x) > T.CreateChecked(y), or even that T(x) is not less than T(y)).
It could be "solved" with a doc comment, and I don't have a real-world example off the top of my head, but I believe that assumption is being made by this proposal, and it's mostly based on common sense more than it is any notion of "rules".
This would be an oversight in the documentation, yes. It is explicitly read/written as a two's complement binary integer to ensure roundtripping and serialization can occur. It does not have to be the shortest 2's complement integer.
but it can't know that the value imported by 0b0010 is necessarily less than the value imported by 0b0100
This shouldn't really be true. The data read is strictly a two's complement integer and so 0b0010 is strictly 2 and 0b0100 is strictly 4. It is then required to throw an OverflowException if the value is not representable as the target type.
The trickiness comes in that someone could have a binary integer that works a bit like floating-point where it saturates and rounds to the nearest representable values, such a type would have implicit bias introduced for its Random implementation if we assume normal distribution.
Such a risk is probably acceptable given such types are likely rare and can override with their own behavior that is suitable for their type.
Even though the existing "Next" is for Int32, the consensus was to use "NextInteger" in case a different generic version of Next was invented later.
We discussed virtual or not, and feel that not-virtual is better (at least for now)
Renamed NextFloat to NextBinaryFloat to leave space for NextDecimalFloat and also to avoid having NextSingle and NextFloat, with the latter not being the same as the float keyword.
The parameterless NextInteger should be capable of returning the MaxValue value (full range).
namespaceSystem;publicpartialclassRandom{// This version should be capable of returning maxValue, not defer to NextInteger(T.MaxValue)publicTNextInteger<T>()whereT:System.Numerics.IBinaryInteger<T>,System.Numerics.IMinMaxValue<T>;publicTNextInteger<T>(TmaxValue)whereT:System.Numerics.IBinaryInteger<T>;publicTNextInteger<T>(TminValue,TmaxValue)whereT:System.Numerics.IBinaryInteger<T>;publicTNextBinaryFloat<T>()whereT:IBinaryFloatingPointIeee754<T>}
The parameterless NextInteger should be capable of returning the MaxValue value (full range).
This works, but it isn't consistent with Next(), which wasn't discussed explicitly in review.
Also this is always 0 to Something, so for signed values, there is still no direct way to get the whole range, although or unsigned values including maxValue does give the full range.
api-approvedAPI was approved in API review, it can be implementedarea-System.Numericsin-prThere is an active PR which will close this issue when it is merged
Activity
danmoseley commentedon Sep 12, 2022
Same for NextSingle() so I think so.
It might be interesting to have a quick look at what random methods other stacks expose.
DrkWzrd commentedon Sep 12, 2022
Humbly I leave here my (not well written) random utilities I use when I need to seed to test something. As example of some useful methods or generics could be integrated
hopperpl commentedon Sep 12, 2022
is maxValue inclusive or exclusive? minValue respectively.
stephentoub commentedon Sep 12, 2022
In the existing APIs, minValue is inclusive and maxValue is exclusive. This is using the same naming as the existing overloads and would have the same semantics as the existing overloads.
hopperpl commentedon Sep 12, 2022
then it should be noted that way...
Next<T>(T.MinValue, T.MaxValue)will not be the same asNext<T>()Next<T>(0, T.MaxValue + 1)will not be possible (assuming T is a signed variant)... if the goal is to have any value of the positive range (of a signed T variant)I'm not against it, but it has to be clearly stated, I fell into that pitfall many times. The documentation mentions it for the current
intimplementation in a small remark. For exampleNext<byte>()can never return 255.I would on a personal note as this is a new implementation without backward compatibility ...
Next<T>()return the full range of TNext<T>(T minInclusive, T maxInclusive)return a complete range -- ormaxExclusivebut have the parameter properly named -- problem with exclusive is still no full positive range possibleif default
Next<float>()would not include 1 then the random value is not usable for the scenarios I use random float numbers.Oh, I forgot to mention, it is easy to turn inclusive to exclusive by subtracting 1 or Epsilon, but it is not possible to do the opposite, as T.MaxValue is the maximum value and nothing can be bigger.
Clockwork-Muse commentedon Sep 12, 2022
Which can cause slight bias to results downstream, as I brought up in #41457 .
.... what are these scenarios?
hopperpl commentedon Sep 12, 2022
raytracing, (audio) signal processing, field density, math, geometry, anything that is too complex to completely calculate... you use a randomization of a normalized set (so 0 to 1) and then calculate until you have enough result values... as the calculation will theoretically go on forever... if the 1 is missing as a random value, one "edge" will be "not sharp"
If you have a large input set, then it doesn't make a difference as by rounding you hit the edge, but sometimes you have a 3 dimensional set or a 4 dimensional set with a very "thin" dimension, for example depth or color/hue (4th dimension). Or you have a reduced data set and the last thing you want is to add a special randomizer for such special cases.
Normalization is usually done with a range of 0 to 1 inclusive. Or -1 to +1 inclusive. The left x-coordinate is 0, the right x-coordinate is 1. Or you have a line from A to B and use a random number to find any point between A and B. But you want A and B both included. A line segment between 2 points includes both points. Normalized, to find A you use 0 and to find B you use 1. In float-color (0,0,0) is Black and (1,1,1) is White, (0.5,0.5,0.5) is Gray etc. The 1 is always part of the set.
aloraman commentedon Sep 12, 2022
Thoughts on API shape
I don't think having the same random API for all numeric types is a good idea. Integer numbers and floating-point numbers have different behaviors and expectations. Single generic API for all of them would have very weird behavior. The very core of RNG is producing sequence of uniformly distributed byte values, other methods produce values of specific types from these byte sequences. With that in mind we can look at differences in numeric types:
System.BytetoSystem.Int64, signed and unsigned) have values that are uniformly distributed. Every interval also has uniformly distributed values. So, producing a binary integer from byte sequence is almost as easy as filling the memory span with these bytes (there are tricks to supportNext(min, max), more on that later). When users callRandom.Next<TBinaryInteger>(min, max), they expect to receive uniformly distributed values.System.Half,System.Single,System.Double) have values that are not uniformly distributed. Some intervals have uniformly distributed numbers, some haven't - it depends on whether only mantissa is changing, or there's a change in value of exponent as well. If we simply fill a memory span with random bytes we won't get a uniform distribution, we'll get a distribution with logarithmic density, which behaves very counter-intuitively. There is a way to produce uniformly distributed values in the interval[0.0; 1.0)utilizing dyadic rationals and the specific size of mantissa, which is used in current implementation. Maybe we can defineNext(max)andNext(min, max)for floating point numbers fromNext(0, 1)via linear transformation, but I'm not sure if that's a good idea - precision loss can skew the distribution.System.Decimal) is its own can of worms, I can't say a lot about it, maybe have specific API for decimals? With a way to pass a specific required precision.Random.Next<BigInteger>()produce? ShouldRandom.Next<Complex>()produce values from full Complex plane or from unit circle?Proposed API shape
Basically,
Next<T>for binary integers should produce values in the same range as existing methods, i.e.,Random.Next<System.Int32>()should behave the same wayRandom.Next()behaves now.Other questions
Next(min, max)for binary integers current implementation uses the range hit test, utilizingLog2Ceiling. Do we haveLog2Ceilingfor every binary integer type? OrLog2+PopCount?[0.0; 1.0)uniform distribution current implementation uses dyadic rationals, utilizing type-specific bit-twiddling. Do we have required constants to implement this bit-twiddling in a generic way?P.S. Maybe it is useful to provide raw span filling method in API, e.g.:
koszeggy commentedon Feb 2, 2023
Before adding newer and newer members toRandomplease consider the API suggestion I proposed in #60549.Breaking Issue Example:The last good example is the introduction ofNextInt64andNextSinglemethods. I have aSecureRandomclass (among others). When .NET 6 was released with the newNextInt64overloads, and before I could release a new version with the new overloads (or even after, if someone targeted .NET 6 without upgrading my libraries),SecureRandom.NextInt64failed to return cryptographically secure results.Even worse (though the issue stands also without this addendum), I actually have a lot of extension methods, forRandom, including someNextInt64overloads that returned secure results before .NET 6 but whenRandom.NextInt64has been introduced, it was not the case anymore until I upgraded my libraries.Possible Solutions:
A. Instead of new
Randommembers please introduce new extension methods that rely on the already existing members of anyRandomimplementation (eg.NextBytes). Just like @DrkWzrd, I also offer myRandomExtensionsfor any possible help/inspiration. Here is a living online example as well.B. As I proposed in #60549, make it possible for a derived implementation to call a protected base constructor that uses an implementation where all virtual members rely on the
Samplemethod as it was in C# 1.x. This not just prevents unnecessary seed initialization in base but also makes the possible new members forward compatible. The non-overridden members will maybe just be a little less optimized until the library is upgradedbut will not fall back to the legacy implementation. I actually even prepared a pull request, in which I followed @GrabYourPitchforks' API review comments, but then unfortunately @stephentoub thought this API was not necessary after all. But now that we face newRandommethods again and the same issues can be expected I kindly ask you to reconsider this statement.Disclaimer:
This API proposal does not indicate the new
Next<T>methods as virtual ones. If they are really non-virtual, then maybe my concerns are not that relevant in this particular case. Still, it would be really helpful to consider my proposal as it addresses the unnecessary allocations issue as well.Correction: I remembered incorrectly: The non-derived compatible implementation of the new
NextInt64method falled back to use multipleNextcaused only a performance issue for mySecureRandomclass but did not affect security. Meaning, my proposed API is no longer needed to implemented before this proposal. It would be only a solution for the unnecessary allocations and slow instantiation, which an independent issue from the new virtual methods. I apologize for creating an unnecessary noise in this issue.stephentoub commentedon Feb 2, 2023
Any new virtuals that are added delegate to an existing abstract/virtual on the type. In the case of the NextInt64 you mentioned, for example, it would delegate to the existing virtual Next(int), calling a derived type's implementation if it existed. So I'm not sure what you mean about it falling back to legacy behavior.
tannergooding commentedon Feb 2, 2023
We have also not historically considered adding new virtual members to be a breaking change. That is exactly how we have to version types (otherwise we'd end up with
RandomEx,RandomV5, etc) and we have nearly always reserved the right to extend our types with additional functionality where appropriate.29 remaining items
vladd commentedon Mar 23, 2026
But what should be the canonical way to obtain a random number from the whole range, including MaxValue? Switching to a bigger size?
NextBytes()?bartonjs commentedon Mar 30, 2026
I feel like I tried something like this from the "batched random" proposal (it ended up with lots of type overloads, and the API Review feedback was "try to make it generic"), and the problem is that IBinaryInteger just says that the value is importable/exportable and it's based on powers of two. It makes no guarantee that the bit pattern of a number that can convert to/from an Int32 value of 2 looks similar to an Int32 with a value of 4.
e.g. imagine an 8-bit number that stores the value of the index into a lookup table for randomized values 0..255 (this is me making a "stop trying to think of an esoteric math function and just say 'mapping table'" timebox limiter), but the math functions all work on the mapped-value rather than the index value.
So, Next(0b0000_0010 (113), 0b0000_0001 (212)) has very unclear behaviors. From a bitwise perspective, max is less than min, but from a value perspective it's bigger, but the only way that I can think of to generate things by flipping bits is (max2 = max - min) and random 0..max2, based on the bit represenation of max2. But that, for my IBinaryInteger here, makes no sense.
Now, we can always document "this is what it does, if your number type does numbers differently than Int32/UInt32, well, sorry, it's gibberish..." but I didn't feel like that would fly in a System.Security namespace. Maybe we're more relaxed for System.Random.
kevincathcart-cas commentedon Apr 14, 2026
IBinaryInteger<TSelf>.ReadLittleEndianis not documented as importing the internal format of the number, but is currently documented as always importing a little endian twos complement number. This would imply (not documented!) that theWriteLittleEndianmust output in that format, otherwise a round trip would change the number. Random certainly can handle making buffers in that format between two values for importing. So either the documentation for that method is wrong, or this should work.However, if the documentation is correct, then this does mean that the interface does not support exporting the number its its native format, which means that if we had a type documented to be stored in some other format like ones compliment or signed magnitude, then for example Toub's
IBinaryInteger<TSelf>.ReverseBitsproposal (#125879)'s DIM would reverse bits in the two's complement representation of an arbitrary IBinaryInteger, not its documented encoding, since the DIM literally would have no way of doing that.bartonjs commentedon Apr 20, 2026
Yeah, random can make a twos-complement binary representation, but it can't know that the value imported by 0b0010 is necessarily less than the value imported by 0b0100. (Maybe somewhere we have that as an explicit expectation, but I don't know that we assert that
x > yimpliesT.CreateChecked(x) > T.CreateChecked(y), or even that T(x) is not less than T(y)).It could be "solved" with a doc comment, and I don't have a real-world example off the top of my head, but I believe that assumption is being made by this proposal, and it's mostly based on common sense more than it is any notion of "rules".
tannergooding commentedon Apr 21, 2026
This would be an oversight in the documentation, yes. It is explicitly read/written as a two's complement binary integer to ensure roundtripping and serialization can occur. It does not have to be the shortest 2's complement integer.
This shouldn't really be true. The data read is strictly a two's complement integer and so
0b0010is strictly2and0b0100is strictly4. It is then required to throw anOverflowExceptionif the value is not representable as the target type.The trickiness comes in that someone could have a binary integer that works a bit like floating-point where it saturates and rounds to the nearest representable values, such a type would have implicit bias introduced for its
Randomimplementation if we assume normal distribution.Such a risk is probably acceptable given such types are likely rare and can override with their own behavior that is suitable for their type.
bartonjs commentedon Apr 21, 2026
Video
floatkeyword.kevincathcart-cas commentedon Apr 21, 2026
This works, but it isn't consistent with
Next(), which wasn't discussed explicitly in review.Also this is always 0 to Something, so for signed values, there is still no direct way to get the whole range, although or unsigned values including maxValue does give the full range.
stephentoub commentedon Apr 27, 2026
It was discussed at ~1:17:00.
Add generic Random NextInteger/NextBinaryFloat APIs (#127462)
Add generic Random NextInteger/NextBinaryFloat APIs (#127462)