VB.net VS2022 => How to generate random number that is a Single or Double
Trying to generate a Single or Double random number between 0 and 1 inclusive of 0 and 1.
I can use rnd() method & it works but everyone on the various VB fora claim this is a bad way to do it (old & pseudorandom length too short)
I have tried "RandomNumberGenerator.GetInt32" and apparently this is a better method but seems to only generate integer values. I need Single/Double capability.
I do not need Crypto (just doing science Monte Carlo calculation) but would love a really long sequence before repeats.
Thanks for any help guys!
Re: VB.net VS2022 => How to generate random number that is a Single or Double
You can just use the Random class to do this:-
Code:
Dim r As New Random
'Generates a random number between 0 and 1
Dim number As Double = r.NextDouble()
Re: VB.net VS2022 => How to generate random number that is a Single or Double
Thank you Niya, I will try this! Looks simple enough. Thank you.
Re: VB.net VS2022 => How to generate random number that is a Single or Double
Note that the upper range is less than 1 so the largest number generated will be something like 0.99...
Re: VB.net VS2022 => How to generate random number that is a Single or Double
Note that both RandomNumberGenerator and Random can generate random Bytes, so you can use those Bytes any way you want, e.g. use BitConverter to convert four Bytes to a Single. That said, you'd probably just use Random.NextDouble and Convert.ToSingle, if a Single is what you need.
Note also that the Random class has had a Shared property since .NET 6, so you don't need to create your own instance anymore, unless you need multiple different instances or to specify your own seed.
Re: VB.net VS2022 => How to generate random number that is a Single or Double
Great input jmcilhinney... this will help get exactly what I need. Appreciate the help from you both!!!