Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 733
Camilo Celis Guzman Avatar asked Oct 20 '25 21:10

Camilo Celis Guzman


2 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)
like image 102
Padraic Cunningham Avatar answered Oct 22 '25 12:10

Padraic Cunningham


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

like image 28
hostingutilities.com Avatar answered Oct 22 '25 11:10

hostingutilities.com



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!