Results 1 to 3 of 3

Thread: How can I generate a negative random number

Hybrid View

  1. #1

    Thread Starter
    New Member
    Join Date
    Feb 2018
    Posts
    7

    Question How can I generate a negative random number

    I would like to generate a floating point value in the range of -1 to +1. I used the following snippet, but it's always positive.

    Me.Text = (-1 * Rnd() +1).ToString

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,344

    Re: How can I generate a negative random number

    Rnd is a holdover from VB6 and should not be used in VB.NET. Unfortunately, many tutorials and classes are written by people who haven't learned anything new in a while, including the last 15 years that .NET has been around. Use the Random class and call its Next method. You simply provide a lower bound and upper bound for the range you want the number to be drawn from. That range can be anywhere from Integer.MinValue to Integer.MaxValue.

  3. #3
    Sinecure devotee
    Join Date
    Aug 2013
    Location
    Southern Tier NY
    Posts
    6,582

    Re: How can I generate a negative random number

    Since Rnd returns a value between 0 and 1, not including 1, as long as you don't need to hit -1.0 or 1.0 then you should think about it.
    -1 to 1 is a range of 2, so generate a number with a range of 0 to 2, i.e. 2*Rnd() and subtract 1.

    Of course since you're using .Net you really should be using the Random Class instead of Rnd.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width