Issue
I have classic integer generator of random numbers.
But I need a random number from 0 to three decimal numbers after the first, the smallest is 0.010 and biggest 9.910.
Example: 0.136 OR 1.539
My code function is this:
Public Function RandomWtring(len As Integer) As String
Dim chars = "0123456789"
Dim str_len = len
Dim randomstring = ""
For i As Integer = 0 To len - 1
Dim rNum = Math.Floor(Rnd() * chars.Length)
randomstring += chars.Substring(rNum, 1)
Next
Return randomstring
End Function
But I dont know how to do the 0.254 example... thx
Solution
Random number generators (RNGs) usually produce a number in the range zero up to (but not including) another number. To generate a random number in a range from min to max, you need to get the size of the range, use the RNG, then scale that back into the desired range.
The VB.NET Rnd() function is not actually a very good RNG; the .NET Random Class is a bit better (there are better in some aspects, but let's not worry about that for this question). All RNGs need some sort of initialisation to start them off, so what you will need to do is have the line
Dim rand As New Random()
somewhere in your code outside the actual function:
Function MyRandomNumber() As String
Dim min As Decimal = 0.01D
Dim max As Decimal = 9.91D
Dim decimalPlaces = 3
Dim multiplier = CDec(Math.Pow(10, decimalPlaces))
Dim range = (max - min) * multiplier
Dim val = rand.Next(0, CInt(range + 1))
Return (val / multiplier + min).ToString()
End Function
I used variables for the minimum and maximum values, and the number of decimal places needed, just in case you need to change them. Also, it is good programming practise to used appropriately-named variables for things like that so that it is easier to understand what is going on if you go back to the code after a few months.
If you need a number rather than a string, change the declaration to
Function MyRandomNumber() As Decimal
and the return line to
Return val / multiplier + min
Answered By - Andrew Morton Answer Checked By - David Goodson (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.