6

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.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
m_vdbeek
  • 3,704
  • 7
  • 46
  • 77
  • You probably don't want to be calling `Random.new` unless you know the consequences of that. Instead just call `rand` by itself. – Andrew Marshall Oct 28 '11 at 17:17
  • Random.rand(-5..5). Please check: http://stackoverflow.com/questions/198460/how-to-get-a-random-number-in-ruby/2773866#2773866 – fotanus May 07 '12 at 04:04

5 Answers5

9

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
Pepe
  • 6,360
  • 5
  • 27
  • 29
  • randomNum = (7-(-8))*prng.rand(0..1) + (-8) Wouldn't this generate a with 50% chance ? (when you have 0 with prng.rand(0..1) – m_vdbeek Oct 28 '11 at 17:20
  • @Awake yes you are correct, use prng.rand instead to generate a random uniform number betwen 0 and 1 – Pepe Oct 28 '11 at 18:48
7

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

Radhika
  • 2,453
  • 2
  • 23
  • 28
5

How about you multiply the positive random number by -1

Mörre
  • 5,699
  • 6
  • 38
  • 63
  • yes but you will get 100% of negative numbers what i want to do is balance between positive / negative numbers if I do prng.rand(-10..10). But this shouldn't work because of the ArgumentError no ? – m_vdbeek Oct 28 '11 at 17:17
  • then go 0...10 and subtract 20! – Mörre Oct 29 '11 at 05:23
3
def rand(a, b)
  return Random.rand(b - a + 1) + a 
end
rand(-3, 5)
Steven Jackson
  • 424
  • 3
  • 8
0

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
thomallen
  • 1,926
  • 1
  • 18
  • 32