random - C# Get only numbers 1-15 from RNGCryptoServiceProvider? -


as rngcryptoserviceprovider "safer" (produces high-quality random numbers) random() felt using it. performance not issue. but, instead of reading last digit, , somehow decide when add 0 or 1 before it.. there better (more accurate) way?

byte[] data = new byte[4]; rng.getbytes(data); int value = bitconverter.toint32(data, 0); console.writeline(value); 

you can use modulo operator (%). leads biased results, 8 byte input bias quite small. smaller bias system.random has.

byte[] data = new byte[8]; rng.getbytes(data); ulong value = bitconverter.touint64(data, 0); result = (int)(value%15+1); 

or if want uniform numbers:

byte[] data = new byte[8]; ulong value; {     rng.getbytes(data);     value = bitconverter.touint64(data, 0); } while(value==0); result = (int)(value%15+1); 

Comments

Popular posts from this blog

matlab - How to equate a structure array to structure array -

c# - Operator '==' incompatible with operand types 'Guid' and 'Guid' using DynamicExpression.ParseLambda<T, bool> -