Generating negative random numbers


#1

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


#2

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: removed_email_address@domain.invalid

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

Want a signature like this?

#3

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


#4

On 1/30/07, Josselin removed_email_address@domain.invalid 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


#5

On 30/01/07, Josselin removed_email_address@domain.invalid 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


#6

On 2007-01-30 08:14:39 +0100, “Gerald E.” removed_email_address@domain.invalid
said:

Direct: 31 53 4893961
-----Original Message-----
From: Josselin [mailto:removed_email_address@domain.invalid]
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 !


#7

On 2007-01-30 08:05:18 +0100, Josselin removed_email_address@domain.invalid 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 …


#8

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