How to generate a random number in the interval [-0.5, 0.5] using Python random() or randrange() functions?
3 Answers
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)
1 Comment
Camilo Celis Guzman
Thank you,
uniform does return a float from the interval [-.5, .5], however, I wanted to know how to do it without using uniform but only random() or randrange()`.this will do the trick random.random() - .5
3 Comments
Camilo Celis Guzman
Thank you! is the upper bound inclusive?
hostingutilities.com
No. The upper bound is exclusive, but the lower bound is inclusive.
hostingutilities.com
random.random() always has an exclusive upper bound, but sometimes random.uniform() will have an inclusive upper bound. Here is a stack overflow question that discusses this further -- stackoverflow.com/questions/5249717/…