help with generating random numbers between -1 and 1

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ILtech
    New Member
    • Oct 2008
    • 6

    help with generating random numbers between -1 and 1

    Math.random() returns a number in the interval [0, 1), right?

    So, if I need to change the interval to (-1, 1), would I use do this...

    xCoord = Math.random() * 2 - 1;

    to change the range to be 2 (so it'd be [0, 2) then subtract one to shift it to (-1, 1)?
  • Laharl
    Recognized Expert Contributor
    • Sep 2007
    • 849

    #2
    This oughtta work, give it a shot.

    Comment

    • teek5449
      New Member
      • Jul 2007
      • 9

      #3
      Don't forget that Math.random() returns a double between 0.0 and 1.0. in order to get the correct results you may need a conditional test.

      Maybe something like (yes tertiary, my professor would kill me :) )

      Code:
      int number = Math.random() >= 0.5 ? 1 : -1;

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Originally posted by ILtech
        Math.random() returns a number in the interval [0, 1), right?

        So, if I need to change the interval to (-1, 1), would I use do this...

        xCoord = Math.random() * 2 - 1;

        to change the range to be 2 (so it'd be [0, 2) then subtract one to shift it to (-1, 1)?
        A small nitpick: if you multiply the range [0,1) by two you get the range [0,2);
        after subtracting one you get the range [-1,1). Note the inclusion on the left
        side and exclusion on the right side.

        The solution is simple: while the original random value happens to be zero,
        generate another random number.

        kind regards,

        Jos

        Comment

        Working...