San*_*4ez 27
>>> import random
>>> random.uniform(-1, 1)
0.4779007751444888
>>> random.uniform(-1, 1)
-0.10028581710574902
Run Code Online (Sandbox Code Playgroud)
import random
def r(minimum, maximum):
return minimum + (maximum - minimum) * random.random()
print r(-1, 1)
Run Code Online (Sandbox Code Playgroud)
编辑:@ San4ez random.uniform(-1, 1)是正确的方法.无需重新发明轮子......
无论如何,random.uniform()编码为:
def uniform(self, a, b):
"Get a random number in the range [a, b) or [a, b] depending on rounding."
return a + (b-a) * self.random()
Run Code Online (Sandbox Code Playgroud)
如果您想要给定区间内的随机整数
例子:
from random import randint
randint(-1,1) --> Randomly returns one of the following: -1, 0, 1
Run Code Online (Sandbox Code Playgroud)
区间 [-1, 1]