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?
>>> import random
>>> random.uniform(-1, 1)
0.4779007751444888
>>> random.uniform(-1, 1)
-0.10028581710574902
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()
def rand(): return 4 # Generated by fair dice roll. Guaranteed to be random.r method is called the same way the correct random.uniform is), just I am reinventing the wheel here… Take San4ez's answer.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
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].
If you want n random values in a positive, negative or mixed range you can use random.sample(range(min,max), population).
The constraint is that distance(max-min) must be lower or equal than population value. In the example above you can generate at most 6 values
>> import random
>> random.sample(range(-3,3), 5)
[-2, -3, 2, -1, 1]
I noticed this today.
random.randint(a, b)
where B > A or B is greater than A
So if we put -999 instead of A and 1 instead of B
It will give us a negative random integer or 0 and 1.
Also, this is a rule in Mathematics, bigger negative numbers are smaller in value than smaller negative numbers, like -999 < -1
This rule can be applied here!