Reputation: 199
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?
Upvotes: 19
Views: 57436
Reputation: 743
If you want to generate 2 random integers between 2 negative values than print(f"{-random.randint(1, 5)}")
can also do the work.
Upvotes: 0
Reputation: 31
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]
Upvotes: 1
Reputation: 58
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!
Upvotes: 0
Reputation: 4219
If you want a random whole number from a given interval
Example:
from random import randint
randint(-1,1) --> Randomly returns one of the following: -1, 0, 1
interval [-1, 1]
Upvotes: 5
Reputation: 1
I find this to work on a list comprehension:
print([x for x in [random.randint(1, 11) * -1]])
or
#int range is n1 to n2
def make_negative(n1, n2):
print([x for x in [random.randint(n1, n2) * -1]])
make_negative(1,10)
Upvotes: 0
Reputation: 8241
>>> import random
>>> random.uniform(-1, 1)
0.4779007751444888
>>> random.uniform(-1, 1)
-0.10028581710574902
Upvotes: 36
Reputation: 1177
You can also do something like this
import random
random.choice([-1, 1])
Upvotes: 1
Reputation: 69052
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
Upvotes: 4
Reputation: 213005
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()
Upvotes: 7
Reputation: 1613
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].
Upvotes: 1