the random function gives you a number between 0.0 and 1.0 . im trying to get a random number between -0.5 and 0.5. i asked someone for help and they told me to go off of this:

[0, 1) + .1

this changes the range to [1, 2) and i tried numerous ways to modify this to get the range im looking for and i've just been tearing my hair out. any type of help, thank you!

4
Contributors
4
Replies
5
Views
7 Years
Discussion Span
Last Post by Gribouillis
``random.uniform(-0.5,0.5)``

the random function gives you a number between 0.0 and 1.0 . im trying to get a random number between -0.5 and 0.5. i asked someone for help and they told me to go off of this:

[0, 1) + .1

this changes the range to [1, 2) and i tried numerous ways to modify this to get the range im looking for and i've just been tearing my hair out. any type of help, thank you!

You never have to tear your hair out when you can't figure out how to use a module like random,
it is documented here:
http://docs.python.org/library/random.html

EDIT: whoops I realized you needed a random number from -.5 to .5

not -5 to 5

There are many ways to do what you are trying to do.
The most straightforward is like this: `random.uniform(-.5,.5)` Here's an alternate way if you didn't know uniform existed,
requires a bit of math thinking: `random.random() - .5`

Edited by jcao219: n/a

sorry i forgot to say i was trying to get a random float number in that range.

You must use an affine transformation

``````def my_random(a, b):
r = random()
return a + r * (b-a)

for i in range(10):
print(my_random(-.5, .5))

"""my output --->
-0.0536919060601
-0.023605782825
-0.154141209554
-0.457966599001
-0.405941049256
0.152834817454
0.22015783989
-0.37435978827
0.0306778666216
0.253595405275
"""``````

Edited by Gribouillis: n/a