CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    May 2006
    Posts
    306

    Random with Min, Max

    How would I generate an integer that is between -1 and 1 with Math.random()?

  2. #2
    Join Date
    Aug 2005
    Location
    Imperial College London, England
    Posts
    490

    Re: Random with Min, Max

    Code:
    function Random(min, max) {
      return (min + (max - min) * Math.random());
    };
    
      //Logic Test: Math.random() = 0
      // min + (0) = min
      // Logic Test: Math.random = 1
      // min + (max - min) = max
    Help from me is always guaranteed!*
    VB.NET code is made up on the spot with VS2008 Professional with .NET 3.5. Everything else is just made up on the spot.
    Please Remember to rate posts, use code tags, send me money and all the other things listed in the "Before you post" posts.

    *Guarantee may not be honoured.

  3. #3
    Join Date
    May 2006
    Posts
    306

    Re: Random with Min, Max

    Thanks, the function is similar to what I found googling.

    Anyways, I think I figured out the one-liner way to do it, which is what I wanted.

    Code:
    var random = Math.random() * -2 + 1;
    Works well.

  4. #4
    Join Date
    Aug 2005
    Location
    Imperial College London, England
    Posts
    490

    Re: Random with Min, Max

    That's exactly the same, you realise. Just replace min with 1 and max with -1
    Help from me is always guaranteed!*
    VB.NET code is made up on the spot with VS2008 Professional with .NET 3.5. Everything else is just made up on the spot.
    Please Remember to rate posts, use code tags, send me money and all the other things listed in the "Before you post" posts.

    *Guarantee may not be honoured.

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

Featured