Negative random numbers

I know how to create numbers with Rails, but I don't know how to create negative numbers?

prng.rand(1..6) for random of [1, 2, 3, 4, 5, 6]

Random doc says you get an ArgumentError.

+5
source share
5 answers

Suppose you want to generate a number between a and b, you can always do this with this formula:

randomNum = (b-a)*prng.rand + a

So, if you need a number from -8 to +7, then a = -8 and b = 7, and your code will be

randomNum = (7-(-8))*prng.rand + (-8)

which is equivalent

randomNum=15*prng.rand - 8
+9
source

Suppose you want to generate negative numbers from -1 to -5

You can simply do this:

rand(-5..-1)

It will generate random numbers from -5 to -1

+6
source

, -1

+5
def rand(a, b)
  return Random.rand(b - a + 1) + a 
end
rand(-3, 5)
+3

I needed to create a random integer, either 1 or -1, and I used this:

prng = Random.new(1)    
prng.rand > 0.5 ? 1 : -1
0
source

All Articles