Camilo Celis Guzman
Camilo Celis Guzman

Reputation: 615

Generate a random number from an interval in Python

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

Upvotes: 4

Views: 21472

Answers (3)

Mario García
Mario García

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

Padraic Cunningham
Padraic Cunningham

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

hostingutilities.com
hostingutilities.com

Reputation: 9509

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

Upvotes: 3

Related Questions