Reputation: 3774
I know how to generate numbers with Rails but I don't know how to generate negative numbers?
prng.rand(1..6) for random of [1, 2, 3, 4, 5, 6]
Random doc says that you would get an ArgumentError.
Upvotes: 6
Views: 3075
Reputation: 2034
I needed to generate a random integer, either 1 or -1 and I used this:
prng = Random.new(1)
prng.rand > 0.5 ? 1 : -1
Upvotes: 0
Reputation: 2559
Suppose you want to generate negative numbers between -1 to -5
You can simply do this:
rand(-5..-1)
It will generate random numbers between -5 to -1
Upvotes: 7
Reputation: 6480
Let's say you want to generate a number between a and b you can always do that using this formula:
randomNum = (b-a)*prng.rand + a
So if you want a number between -8 and +7 for example then a=-8 and b=7 and your code would be
randomNum = (7-(-8))*prng.rand + (-8)
which is equivalent to
randomNum=15*prng.rand - 8
Upvotes: 9
Reputation: 434
def rand(a, b)
return Random.rand(b - a + 1) + a
end
rand(-3, 5)
Upvotes: 3