如何在python中生成负的随机值

use*_*251 11 python random

我开始学习python,我尝试通过传递负数和正数来生成随机值.让说 -1,1.

我应该如何在python中执行此操作?

San*_*4ez 27

使用 random.uniform(a, b)

>>> import random
>>> random.uniform(-1, 1)
0.4779007751444888
>>> random.uniform(-1, 1)
-0.10028581710574902
Run Code Online (Sandbox Code Playgroud)


eum*_*iro 5

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)


Seb*_*sen 5

如果您想要给定区间内的随机整数

例子:

from random import randint
randint(-1,1)               --> Randomly returns one of the following: -1, 0, 1
Run Code Online (Sandbox Code Playgroud)

区间 [-1, 1]