11 Replies Latest reply on Mar 29, 2008 7:31 AM by Wolfgang Herold

# random with negative numbers

Hello:
Can you help to make a random that is between -8 and 8 for example?
I mean, between -8,-7,-6,-5,-4,-3,-2,-1,1,2,3,4,5,6,7,8.

Thank you very much

• ###### 1. Re: random with negative numbers
Did you purposely remove the zero? This will get a standard -8 through
8 (including zero)

put random(17)-9
• ###### 2. Re: random with negative numbers
random(-8,8)
• ###### 3. Re: random with negative numbers
random(-8,8)
• ###### 4. Re: random with negative numbers
random(-8,8)
• ###### 5. Re: random with negative numbers
Oh good catch with the zero Mike! I didn't see that. I guess if you
didn't want to include zero you could set a global variable

gRandomChoices = [-8,-7,-6,-5,-4,-3,-2,-1,1,2,3,4,5,6,7,8]

and then

put gRandomChoices[random(gRandomChoices.count)]

Is there another way?
• ###### 6. Re: random with negative numbers
Or something like this:

aRandom=random(8)
aSign=random(2)
if aSign=1 then
aRandom=0-aRandom
end if
put aRandom
• ###### 7. Re: random with negative numbers
what about "myrand(-8,8)"

on myrand ( x,y)
a = random(x,y-1)
if a = 0 then a = y
return a
end

Wolfgang
• ###### 8. Re: random with negative numbers
So there you have it! At least 3 different ways of generating the random
numbers you need, without including zero.

Curiosity got the better of me, and I wondered which was faster. I made
a test, each method generating 5,000,000 random numbers. I ran this test
several times and the results were fairly consistent

And the winner is

#1 Wolfgang ~ 159 ticks
#2 Dave ~ 168 ticks
#3 Mike ~ 210 ticks

• ###### 9. Re: random with negative numbers
Oops, I made a slight mistake, Wolfgang's method was a bit faster than I
reported

#1 Wolfgang ~ 148 ticks
#2 Dave ~ 168 ticks
#3 Mike ~ 210 ticks

• ###### 10. Re: random with negative numbers
Nice!
• ###### 11. Re: random with negative numbers
Great, as in another thread defined and discused, i am
a scripter, not a programmer, but i like oaying with math.
Daves method is easy, but what about Random( -300,1200).
that must be a huge array to initialize.
my function has a restriction:
it works only, if there is a zero in the range or you'll never get the highest number of the range. Also it can only have a linear range.

Dave can input a list like this gRandomChoises = [ 1,3,5,7,11,13,17] , what can be very usefull in some cases.

Cheers,
Wolfgang