4

How to generate a random number in the interval [-0.5, 0.5] using Python random() or randrange() functions?

0

3 Answers 3

9

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)
Sign up to request clarification or add additional context in comments.

1 Comment

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()`.
3

this will do the trick random.random() - .5

3 Comments

Thank you! is the upper bound inclusive?
No. The upper bound is exclusive, but the lower bound is inclusive.
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/…
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.