Take the 2-minute tour ×

I am a newbie. So starting to learn python, I tried to generate random values by passing in a negative and positive number.

Let say -1, 1. Can someone let me know how I should do this in python.

Thanks in advance

share|improve this question
add comment

5 Answers

>>> import random
>>> random.uniform(-1, 1)
>>> random.uniform(-1, 1)


share|improve this answer
+1 This is of course the way to go. –  eumiro May 14 '12 at 8:10
add comment
import random

def r(minimum, maximum):
    return minimum + (maximum - minimum) * random.random()

print r(-1, 1)

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

Anyway, random.uniform() is coded as:

def uniform(self, a, b):
    "Get a random number in the range [a, b) or [a, b] depending on rounding."
    return a + (b-a) * self.random()
share|improve this answer
def rand(): return 4 # Generated by fair dice roll. Guaranteed to be random. –  Li-aung Yip May 14 '12 at 8:09
Thanks a lot.But cann't i do in this way.Where i want to pass the value as a argument while running the script. .#!/usr/bin/env python import sys , random r = sys.argv[1] y = sys.argv[2] print random.range(y,r) –  user1393251 May 14 '12 at 8:10
@user1393251 - you can do it this way (my r method is called the same way the correct random.uniform is), just I am reinventing the wheel here… Take San4ez's answer. –  eumiro May 14 '12 at 8:13
add comment

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

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

By doubling the number we get a range of [0, 2], and by subtracting one from it, we get [-1, 1].

share|improve this answer
add comment

if you want integer in a 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 similar if you need float values, but it's not always clear if the upper limit is included or not

share|improve this answer
add comment

You can also do something like this

import random
random.choice([-1, 1])
share|improve this answer
add comment

Your Answer


