VBA generating random numbers between -35 to +5

Yags

I'm trying to code a line in VBA that would allow me to generate random numbers between -35 and 5. I've used the below formula however, it gives me random numbers between -5 and +5

Int((Rnd() * ((-1) ^ Int(Rnd() * 10))) * 5)
Bathsheba
Fix(Rnd() * 41) - 35

will do it. This will be uniformly distributed insofar that Rnd() is. Fix scrubs the decimal portion of a number. You want every number between -35 and 5 inclusive which is 41 numbers. rnd() itself never draws 1.

Test the generator with something like

Sub test()

    Dim j As Long
    While True
        j = Fix(Rnd() * 41) - 35

        VBA.DoEvents 'so you can break the program once you're done

        If j < -35 Or j > 5 Then
            Stop 'oops
        End If
        If j = -35 Then
            Debug.Print "Yup, I draw on the boundary"
        End If
        If j = 5 Then
            Debug.Print "Yup, I draw on the boundary"
        End If
    Wend

End Sub

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related