Yags
Yags

Reputation: 522

VBA generating random numbers between -35 to +5

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)

Upvotes: 1

Views: 622

Answers (2)

LS_ᴅᴇᴠ
LS_ᴅᴇᴠ

Reputation: 11181

If you want an uniform distribution:

Int(Rnd*41)-35

0<=Rnd<1 (some time back I found Rnd=1, but it seams not happening any more)

0<=Rnd*41<41

0<=Int(Rnd*41)<=40

-35<=Int(Rnd*41)-35<=5

From documentation:

Int
Returns the integer portion of a number.

Upvotes: 2

Bathsheba
Bathsheba

Reputation: 234795

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

Upvotes: 3

Related Questions