Generating negative random numbers

I know how to generate positive random numbers, but is it possible to
generate a random number in a range such [-9…+9] ?
tfyh

joss

Rand(18)-9

Gerald E.
Laser Technician

NCLR B.V.
PO box 2662
Enschede 7500CR
The Netherlands
Work: 31 53 4891110
Direct: 31 53 4893961
Fax: 31 53 4891102
Email: [email protected]

http://www.linkedin.com/in/geraldebberink

Want a signature like this?

On Jan 29, 2007, at 11:10 PM, Josselin wrote:

I know how to generate positive random numbers, but is it possible
to generate a random number in a range such [-9…+9] ?

irb(main):001:0> def rrand(x)
irb(main):002:1> rand(2*x) - x
irb(main):003:1> end
=> nil
irb(main):004:0> rrand 9
=> -7
irb(main):005:0> rrand 9
=> -8
irb(main):006:0> rrand 9
=> 5
irb(main):007:0> rrand 9
=> -8

On 1/30/07, Josselin [email protected] wrote:

I know how to generate positive random numbers, but is it possible to
generate a random number in a range such [-9…+9] ?
tfyh

class Range
def rand
Kernel::rand(last - first + 1) + first
end
end

(-9…9).rand

martin

On 30/01/07, Josselin [email protected] wrote:

I know how to generate positive random numbers, but is it possible to
generate a random number in a range such [-9…+9] ?
tfyh

joss

rand(19) - 9

Farrel

On 2007-01-30 08:14:39 +0100, “Gerald E.” [email protected]
said:

Direct: 31 53 4893961
-----Original Message-----
From: Josselin [mailto:[email protected]]
Sent: dinsdag 30 januari 2007 8:10
To: ruby-talk ML
Subject: generating negative random numbers

I know how to generate positive random numbers, but is it possible to
generate a random number in a range such [-9…+9] ?
tfyh

joss

thanks … I’d never think about it !

On 2007-01-30 08:05:18 +0100, Josselin [email protected] said:

I know how to generate positive random numbers, but is it possible to
generate a random number in a range such [-9…+9] ?
tfyh

joss

thanks to all of u, got it, but why there is no ‘standard’ function in
the lib …

On Jan 30, 2007, at 08:52 , Martin DeMello wrote:

(-9…9).rand

(-9…10).rand won’t give the expected answer. I think the below
should fix the problem when the last entry in the range is excluded:

class Range
def rand
return first if exclude_end? && last == first
Kernel::rand(last - first + (exclude_end? ? 0 : 1)) + first
end
end

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs