从Python中的间隔生成随机数

时间:2022-11-15 00:58:10

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

如何使用Python random()或randrange()函数在区间[-0.5,0.5]中生成随机数?

2 个解决方案

#1


1  

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

这将做的技巧random.random() - .5

#2


1  

random returns a float and takes no arguments, randrange takes an upper and lower bound but takes and returns an int.

random返回一个float并且不带参数,randrange采用上限和下限但是接受并返回一个int。

from random import randrange

print(randrange(-5, 5))

If you want floats use uniform:

如果你想要花车使用制服:

from random import  uniform

uniform(-.5, .5)

#1


1  

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

这将做的技巧random.random() - .5

#2


1  

random returns a float and takes no arguments, randrange takes an upper and lower bound but takes and returns an int.

random返回一个float并且不带参数,randrange采用上限和下限但是接受并返回一个int。

from random import randrange

print(randrange(-5, 5))

If you want floats use uniform:

如果你想要花车使用制服:

from random import  uniform

uniform(-.5, .5)