Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negative random numbers

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.

like image 546
m_vdbeek Avatar asked Oct 28 '11 17:10

m_vdbeek


2 Answers

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
like image 146
Pepe Avatar answered Oct 11 '22 14:10

Pepe


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

like image 24
Radhika Avatar answered Oct 11 '22 13:10

Radhika