Reputation: 615
How to generate a random number in the interval [-0.5, 0.5] using Python random()
or randrange()
functions?
Upvotes: 4
Views: 21472
Reputation: 182
If you want to stick with random()
and use a varying bound, you could easily do:
from random import random
upper_limit = 0.5
lower_limit = -0.5
random() * (upper_limit - lower_limit) + lower_limit
This will always give you a random float between -0.5 and 0.5.
Upvotes: 2
Reputation: 180391
random returns a float and takes no arguments, randrange takes an upper and lower bound but takes and returns an int.
from random import randrange
print(randrange(-5, 5))
If you want floats use uniform:
from random import uniform
uniform(-.5, .5)
Upvotes: 9