Help | Site Map
Connecting Tech Pros Worldwide
Reply
 
LinkBack Thread Tools
  #1  
Old October 3rd, 2008, 08:49 PM
ILtech's Avatar
Newbie
 
Join Date: Oct 2008
Posts: 6
Default 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)?
Reply
  #2  
Old October 3rd, 2008, 10:11 PM
Expert
 
Join Date: Sep 2007
Posts: 849
Default

This oughtta work, give it a shot.
Reply
  #3  
Old October 4th, 2008, 01:45 AM
Newbie
 
Join Date: Jul 2007
Posts: 6
Default

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 :) )

Expand|Select|Wrap|Line Numbers
  1. int number = Math.random() >= 0.5 ? 1 : -1;
Reply
  #4  
Old October 4th, 2008, 07:49 AM
Moderator
 
Join Date: Mar 2007
Location: Voorschoten, the Netherlands
Age: 52
Posts: 8,495
Default

Quote:
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
Reply
Reply

Bookmarks

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are Off
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

What is Bytes?

We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights. Get the best answers to your questions from over network members.
Post your question now . . .
It's fast and it's free

Popular Articles