Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate negative random value in python

Tags:

python

random

I am starting to learn python, I tried to generate random values by passing in a negative and positive number. Let say -1, 1.

How should I do this in python?

like image 450
user1393251 Avatar asked May 14 '12 08:05

user1393251


People also ask

How do you get negative values in Python?

Python Code:n = float(input("Input a number: ")) if n >= 0: if n == 0: print("It is Zero! ") else: print("Number is Positive number. ") else: print("Number is Negative number. ")

Can rand () return negative?

Note that rand()+1 is used to avoid 0 ; rand() does not return a negative value.

Can INT take negative values in Python?

All the negative and positive numbers along with 0 comprise integers. Thus, the numbers that are greater than 0 are positive, whole numbers lesser than 0 are referred to as negative. This is the concept used in Python is negative program.


2 Answers

Use random.uniform(a, b)

>>> import random
>>> random.uniform(-1, 1)
0.4779007751444888
>>> random.uniform(-1, 1)
-0.10028581710574902
like image 191
San4ez Avatar answered Oct 27 '22 15:10

San4ez


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()
like image 30
eumiro Avatar answered Oct 27 '22 15:10

eumiro