How to generate negative random value in python

I'm starting to learn python, I tried to generate random values ​​by passing a negative and a positive number. Say -1 , 1 .

How do I do this in python?

+8
python random
source share
5 answers

Use random.uniform(a, b)

 >>> import random >>> random.uniform(-1, 1) 0.4779007751444888 >>> random.uniform(-1, 1) -0.10028581710574902 
+24
source share
 import random def r(minimum, maximum): return minimum + (maximum - minimum) * random.random() print r(-1, 1) 

EDIT: @ San4ez random.uniform(-1, 1) is the right way. No need to reinvent the wheel ...

In any case, random.uniform() is encoded as:

 def uniform(self, a, b): "Get a random number in the range [a, b) or [a, b] depending on rounding." return a + (ba) * self.random() 
+5
source share

if you want an integer in the specified range :

 print random.randrange(-1, 2) 

it uses the same convention as range , so the upper limit is not included.

random.uniform does something like this if you need float values, but not always cleared if the upper limit is enabled or not

+2
source share

Most languages ​​have a function that will return a random number in the range [0, 1], which you can then manipulate to select the desired range. In python, the random.random function. So for your range [-1, 1] you can do this:

 import random random_number = random.random() * 2 - 1 

By doubling the number, we get the range [0, 2] and subtract it from it, we get [-1, 1].

+1
source share

You can also do something like this

 import random random.choice([-1, 1]) 
+1
source share

All Articles