dcsimg
Results 1 to 3 of 3
  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
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    98,683

    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.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3
    Sinecure devotee
    Join Date
    Aug 2013
    Location
    Southern Tier NY
    Posts
    4,410

    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
  •  



Featured


Click Here to Expand Forum to Full Width


×
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.