Quantcast
Channel: Latest Questions by esitoinatteso
Viewing all articles
Browse latest Browse all 92

More True Randomess - RNGCryptoServiceProvider explanation required

$
0
0
Hay there, it's been a while but now I have a new Question!!! :D I wrote some code that needed randomness and then checked the results "UnityEngine.Random()" was returning . I didn't liked the way it presented a pattern in values that were supposed to be " random". I was aware that sort of randomness wasn't the so called **true randomness** but still I thought it could achieve better results. **I ended up using the RNGCryptoServiceProvider class from Microsoft for a " higher" quality of randomness.** This is the code I used, I basically copy-pasted the logic they explain in their reference page: int RandomWithRNGcryptography(int range){ //Set up RNG for more randomness RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); //Convert range from int to byte byte bRange = (byte) range; byte[] arr = new byte[1]; do{ rng.GetBytes(arr); } while(!IsFairRandom(arr[0],bRange)); return (int)((arr[0] % bRange) +1); } bool IsFairRandom(byte number,byte range){ range = range>0?range:(byte)1; int fullSetOfValues = Byte.MaxValue /range; return number < range * fullSetOfValues; } **MY QUESTION IS... CAN YOU GUYS EXPLAIN THAT STUFF TO ME? O.O** I've checked the numbers this returns and all is doing well, now I would like to know why everything is working because I haven't done much more than copy-pasting logic I don't understand :/ Also, I had to set up a conditional assignment in the bool because sometimes it divided by zero... I don't understand though! *Extra Mile: why Unity only uses UnityEngine.Random(), that approximates sometimes too much for something supposedly random?* Please help me learning and thanks a bunch!!!

Viewing all articles
Browse latest Browse all 92

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>