生成 0 到 9 之间的随机整数

发布于 2024-09-28 07:43:47 字数 224 浏览 4 评论 0原文

如何在Python中生成09(含)之间的随机整数?

例如,01234>56789

How can I generate random integers between 0 and 9 (inclusive) in Python?

For example, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(23

自演自醉 2024-10-05 07:43:47

尝试 random.randrange

from random import randrange
print(randrange(10))

Try random.randrange:

from random import randrange
print(randrange(10))
看轻我的陪伴 2024-10-05 07:43:47

尝试 random.randint

import random
print(random.randint(0, 9))

文档状态:

random.randint(a, b)

返回一个随机整数N,使得a <= N <= brandrange(a, b+1) 的别名。

Try random.randint:

import random
print(random.randint(0, 9))

Docs state:

random.randint(a, b)

Return a random integer N such that a <= N <= b. Alias for randrange(a, b+1).

我恋#小黄人 2024-10-05 07:43:47

试试这个:

from random import randrange, uniform

# randrange gives you an integral value
irand = randrange(0, 10)

# uniform gives you a floating-point value
frand = uniform(0, 10)

Try this:

from random import randrange, uniform

# randrange gives you an integral value
irand = randrange(0, 10)

# uniform gives you a floating-point value
frand = uniform(0, 10)
小清晰的声音 2024-10-05 07:43:47
from random import randint

x = [randint(0, 9) for p in range(0, 10)]

这会生成 10 个介于 0 到 9 之间的伪随机整数。

from random import randint

x = [randint(0, 9) for p in range(0, 10)]

This generates 10 pseudorandom integers in range 0 to 9 inclusive.

抹茶夏天i‖ 2024-10-05 07:43:47

secrets 模块是新的Python 3.6。这比 random 更好用于加密或安全用途的模块。

要随机打印 0-9 范围内的整数:

from secrets import randbelow
print(randbelow(10))

有关详细信息,请参阅 PEP 506< /a>.

请注意,这实际上取决于用例。使用 random 模块,您可以设置随机种子,这对于伪随机但可重现的结果很有用,而使用 secrets 模块则无法做到这一点。

random 模块也更快(在 Python 3.9 上测试):

>>> timeit.timeit("random.randrange(10)", setup="import random")
0.4920286529999771
>>> timeit.timeit("secrets.randbelow(10)", setup="import secrets")
2.0670733770000425

The secrets module is new in Python 3.6. This is better than the random module for cryptography or security uses.

To randomly print an integer in the inclusive range 0-9:

from secrets import randbelow
print(randbelow(10))

For details, see PEP 506.

Note that it really depends on the use case. With the random module you can set a random seed, useful for pseudorandom but reproducible results, and this is not possible with the secrets module.

random module is also faster (tested on Python 3.9):

>>> timeit.timeit("random.randrange(10)", setup="import random")
0.4920286529999771
>>> timeit.timeit("secrets.randbelow(10)", setup="import secrets")
2.0670733770000425
马蹄踏│碎落叶 2024-10-05 07:43:47

我会尝试以下其中一项:

1.> numpy.random.randint

import numpy as np
X1 = np.random.randint(low=0, high=10, size=(15,))

print (X1)
>>> array([3, 0, 9, 0, 5, 7, 6, 9, 6, 7, 9, 6, 6, 9, 8])

2.> numpy.random.uniform

import numpy as np
X2 = np.random.uniform(low=0, high=10, size=(15,)).astype(int)

print (X2)
>>> array([8, 3, 6, 9, 1, 0, 3, 6, 3, 3, 1, 2, 4, 0, 4])

3.> numpy.random.choice

import numpy as np
X3 = np.random.choice(a=10, size=15 )

print (X3)
>>> array([1, 4, 0, 2, 5, 2, 7, 5, 0, 0, 8, 4, 4, 0, 9])

4.> random.randrange

from random import randrange
X4 = [randrange(10) for i in range(15)]

print (X4)
>>> [2, 1, 4, 1, 2, 8, 8, 6, 4, 1, 0, 5, 8, 3, 5]

5.> ; random.randint

from random import randint
X5 = [randint(0, 9) for i in range(0, 15)]

print (X5)
>>> [6, 2, 6, 9, 5, 3, 2, 3, 3, 4, 4, 7, 4, 9, 6]

速度:

np.random.uniform 和 np.random.randintnp.random.choice、random.randrange、random 快得多(大约快 10 倍)。兰特。

%timeit np.random.randint(low=0, high=10, size=(15,))
>> 1.64 µs ± 7.83 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit np.random.uniform(low=0, high=10, size=(15,)).astype(int)
>> 2.15 µs ± 38.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit np.random.choice(a=10, size=15 )
>> 21 µs ± 629 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

%timeit [randrange(10) for i in range(15)]
>> 12.9 µs ± 60.4 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit [randint(0, 9) for i in range(0, 15)]
>> 20 µs ± 386 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

注释:

1.> np.random.randint 生成随机整数半开区间 [低点,高点)。

2.> np.random.uniform 生成均匀分布的数字在半开区间[最低点,最高点)。

3.> np.random.choice 在半开区间 [low, high) 上生成随机样本,就好像参数 a 是 np.arange(n)。

4.> random.randrange(stop) 从 range(开始、停止、步骤)。

5.> random.randint(a, b) 返回一个随机整数 N,使得 a < ;= N <= b。

6.> astype(int) 转换numpy 数组转换为 int 数据类型。

7.>我选择了大小=(15,)。这将为您提供一个长度 = 15 的 numpy 数组。

I would try one of the following:

1.> numpy.random.randint

import numpy as np
X1 = np.random.randint(low=0, high=10, size=(15,))

print (X1)
>>> array([3, 0, 9, 0, 5, 7, 6, 9, 6, 7, 9, 6, 6, 9, 8])

2.> numpy.random.uniform

import numpy as np
X2 = np.random.uniform(low=0, high=10, size=(15,)).astype(int)

print (X2)
>>> array([8, 3, 6, 9, 1, 0, 3, 6, 3, 3, 1, 2, 4, 0, 4])

3.> numpy.random.choice

import numpy as np
X3 = np.random.choice(a=10, size=15 )

print (X3)
>>> array([1, 4, 0, 2, 5, 2, 7, 5, 0, 0, 8, 4, 4, 0, 9])

4.> random.randrange

from random import randrange
X4 = [randrange(10) for i in range(15)]

print (X4)
>>> [2, 1, 4, 1, 2, 8, 8, 6, 4, 1, 0, 5, 8, 3, 5]

5.> random.randint

from random import randint
X5 = [randint(0, 9) for i in range(0, 15)]

print (X5)
>>> [6, 2, 6, 9, 5, 3, 2, 3, 3, 4, 4, 7, 4, 9, 6]

Speed:

np.random.uniform and np.random.randint are much faster (~10 times faster) than np.random.choice, random.randrange, random.randint .

%timeit np.random.randint(low=0, high=10, size=(15,))
>> 1.64 µs ± 7.83 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit np.random.uniform(low=0, high=10, size=(15,)).astype(int)
>> 2.15 µs ± 38.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit np.random.choice(a=10, size=15 )
>> 21 µs ± 629 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

%timeit [randrange(10) for i in range(15)]
>> 12.9 µs ± 60.4 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit [randint(0, 9) for i in range(0, 15)]
>> 20 µs ± 386 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Notes:

1.> np.random.randint generates random integers over the half-open interval [low, high).

2.> np.random.uniform generates uniformly distributed numbers over the half-open interval [low, high).

3.> np.random.choice generates a random sample over the half-open interval [low, high) as if the argument a was np.arange(n).

4.> random.randrange(stop) generates a random number from range(start, stop, step).

5.> random.randint(a, b) returns a random integer N such that a <= N <= b.

6.> astype(int) casts the numpy array to int data type.

7.> I have chosen size = (15,). This will give you a numpy array of length = 15.

三生一梦 2024-10-05 07:43:47

选择数组的大小(在本例中,我选择的大小为 20)。然后,使用以下内容:

import numpy as np   
np.random.randint(10, size=(1, 20))

您可以期望看到以下形式的输出(每次运行时都会返回不同的随机整数;因此您可以期望输出数组中的整数与给定的示例不同下面)。

array([[1, 6, 1, 2, 8, 6, 3, 3, 2, 5, 6, 5, 0, 9, 5, 6, 4, 5, 9, 3]])

Choose the size of the array (in this example, I have chosen the size to be 20). And then, use the following:

import numpy as np   
np.random.randint(10, size=(1, 20))

You can expect to see an output of the following form (different random integers will be returned each time you run it; hence you can expect the integers in the output array to differ from the example given below).

array([[1, 6, 1, 2, 8, 6, 3, 3, 2, 5, 6, 5, 0, 9, 5, 6, 4, 5, 9, 3]])
星星的轨迹 2024-10-05 07:43:47

虽然许多帖子演示了如何获取一个随机整数,但最初的问题是如何生成随机整数s(复数):

如何在 Python 中生成 0 到 9(含)之间的随机整数?

为了清楚起见,这里我们演示如何获取多个随机整数。

给定

>>> import random


lo = 0
hi = 10
size = 5

代码

多个随机整数

# A
>>> [lo + int(random.random() * (hi - lo)) for _ in range(size)]
[5, 6, 1, 3, 0]

# B
>>> [random.randint(lo, hi) for _ in range(size)]
[9, 7, 0, 7, 3]

# C
>>> [random.randrange(lo, hi) for _ in range(size)]
[8, 3, 6, 8, 7]

# D
>>> lst = list(range(lo, hi))
>>> random.shuffle(lst)
>>> [lst[i] for i in range(size)]
[6, 8, 2, 5, 1]

# E
>>> [random.choice(range(lo, hi)) for _ in range(size)]
[2, 1, 6, 9, 5]

随机整数样本

# F
>>> random.choices(range(lo, hi), k=size)
[3, 2, 0, 8, 2]

# G
>>> random.sample(range(lo, hi), k=size)
[4, 5, 1, 2, 3]

详细信息

一些帖子演示了如何本机生成多个随机整数。1以下是解决隐含问题的一些选项:

另请参阅 R. Hettinger 的演讲使用 random 模块中的示例来了解分块和别名。

以下是标准库和 Numpy 中一些随机函数的比较:

| | random                | numpy.random                     |
|-|-----------------------|----------------------------------|
|A| random()              | random()                         |
|B| randint(low, high)    | randint(low, high)               |
|C| randrange(low, high)  | randint(low, high)               |
|D| shuffle(seq)          | shuffle(seq)                     |
|E| choice(seq)           | choice(seq)                      |
|F| choices(seq, k)       | choice(seq, size)                |
|G| sample(seq, k)        | choice(seq, size, replace=False) |

您还可以快速转换许多 Numpy 中对随机整数样本的分布3

示例

>>> np.random.normal(loc=5, scale=10, size=size).astype(int)
array([17, 10,  3,  1, 16])

>>> np.random.poisson(lam=1, size=size).astype(int)
array([1, 3, 0, 2, 0])

>>> np.random.lognormal(mean=0.0, sigma=1.0, size=size).astype(int)
array([1, 3, 1, 5, 1])

1< /sup>即@John Lawrence Aspden、@ST Mohammed、@SiddTheKid、@user14372、@zangw 等人
2@prashanth 提到此模块显示一个整数。
3由@Siddharth Satpathy演示

While many posts demonstrate how to get one random integer, the original question asks how to generate random integers (plural):

How can I generate random integers between 0 and 9 (inclusive) in Python?

For clarity, here we demonstrate how to get multiple random integers.

Given

>>> import random


lo = 0
hi = 10
size = 5

Code

Multiple, Random Integers

# A
>>> [lo + int(random.random() * (hi - lo)) for _ in range(size)]
[5, 6, 1, 3, 0]

# B
>>> [random.randint(lo, hi) for _ in range(size)]
[9, 7, 0, 7, 3]

# C
>>> [random.randrange(lo, hi) for _ in range(size)]
[8, 3, 6, 8, 7]

# D
>>> lst = list(range(lo, hi))
>>> random.shuffle(lst)
>>> [lst[i] for i in range(size)]
[6, 8, 2, 5, 1]

# E
>>> [random.choice(range(lo, hi)) for _ in range(size)]
[2, 1, 6, 9, 5]

Sample of Random Integers

# F
>>> random.choices(range(lo, hi), k=size)
[3, 2, 0, 8, 2]

# G
>>> random.sample(range(lo, hi), k=size)
[4, 5, 1, 2, 3]

Details

Some posts demonstrate how to natively generate multiple random integers.1 Here are some options that address the implied question:

See also R. Hettinger's talk on Chunking and Aliasing using examples from the random module.

Here is a comparison of some random functions in the Standard Library and Numpy:

| | random                | numpy.random                     |
|-|-----------------------|----------------------------------|
|A| random()              | random()                         |
|B| randint(low, high)    | randint(low, high)               |
|C| randrange(low, high)  | randint(low, high)               |
|D| shuffle(seq)          | shuffle(seq)                     |
|E| choice(seq)           | choice(seq)                      |
|F| choices(seq, k)       | choice(seq, size)                |
|G| sample(seq, k)        | choice(seq, size, replace=False) |

You can also quickly convert one of many distributions in Numpy to a sample of random integers.3

Examples

>>> np.random.normal(loc=5, scale=10, size=size).astype(int)
array([17, 10,  3,  1, 16])

>>> np.random.poisson(lam=1, size=size).astype(int)
array([1, 3, 0, 2, 0])

>>> np.random.lognormal(mean=0.0, sigma=1.0, size=size).astype(int)
array([1, 3, 1, 5, 1])

1Namely @John Lawrence Aspden, @S T Mohammed, @SiddTheKid, @user14372, @zangw, et al.
2@prashanth mentions this module showing one integer.
3Demonstrated by @Siddharth Satpathy

时间你老了 2024-10-05 07:43:47

您需要 random python 模块,它是标准库的一部分。
使用代码...

from random import randint

num1= randint(0,9)

这会将变量 num1 设置为 09 之间的随机数(含)。

You need the random python module which is part of your standard library.
Use the code...

from random import randint

num1= randint(0,9)

This will set the variable num1 to a random number between 0 and 9 inclusive.

留蓝 2024-10-05 07:43:47

通过 random.shuffle 尝试一下

>>> import random
>>> nums = range(10)
>>> random.shuffle(nums)
>>> nums
[6, 3, 5, 4, 0, 1, 2, 9, 8, 7]

Try this through random.shuffle

>>> import random
>>> nums = range(10)
>>> random.shuffle(nums)
>>> nums
[6, 3, 5, 4, 0, 1, 2, 9, 8, 7]
花落人断肠 2024-10-05 07:43:47

如果是连续数字 randint 或 < a href="https://docs.python.org/library/random.html#random.randrange" rel="noreferrer">randrange 可能是最好的选择,但如果您序列中有几个不同的值(即 list),您也可以使用 choice

>>> import random
>>> values = list(range(10))
>>> random.choice(values)
5

choice 也适用于不连续样本中的一项:

>>> values = [1, 2, 3, 5, 7, 10]
>>> random.choice(values)
7

如果您需要它“加密强度高”,还有一个 secrets.choice 在 python 3.6 及更高版本中:

>>> import secrets
>>> values = list(range(10))
>>> secrets.choice(values)
2

In case of continuous numbers randint or randrange are probably the best choices but if you have several distinct values in a sequence (i.e. a list) you could also use choice:

>>> import random
>>> values = list(range(10))
>>> random.choice(values)
5

choice also works for one item from a not-continuous sample:

>>> values = [1, 2, 3, 5, 7, 10]
>>> random.choice(values)
7

If you need it "cryptographically strong" there's also a secrets.choice in python 3.6 and newer:

>>> import secrets
>>> values = list(range(10))
>>> secrets.choice(values)
2
山田美奈子 2024-10-05 07:43:47

如果你想使用 numpy 那么使用以下命令:

import numpy as np
print(np.random.randint(0,10))

if you want to use numpy then use the following:

import numpy as np
print(np.random.randint(0,10))
旧时模样 2024-10-05 07:43:47
>>> import random
>>> random.randrange(10)
3
>>> random.randrange(10)
1

要获取十个样本的列表:

>>> [random.randrange(10) for x in range(10)]
[9, 0, 4, 0, 5, 7, 4, 3, 6, 8]
>>> import random
>>> random.randrange(10)
3
>>> random.randrange(10)
1

To get a list of ten samples:

>>> [random.randrange(10) for x in range(10)]
[9, 0, 4, 0, 5, 7, 4, 3, 6, 8]
围归者 2024-10-05 07:43:47

您可以尝试从 Python 导入 random 模块,然后让它在九个数字中进行选择。这真的很基本。

import random
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

    

如果稍后要使用计算机选择的值,则可以尝试将其放入变量中,但如果不使用,则打印函数应按如下方式工作:

choice = random.choice(numbers)
print(choice)

You can try importing the random module from Python and then making it choose a choice between the nine numbers. It's really basic.

import random
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

    

You can try putting the value the computer chose in a variable if you're going to use it later, but if not, the print function should work as such:

choice = random.choice(numbers)
print(choice)
锦上情书 2024-10-05 07:43:47

生成 0 到 9 之间的随机整数。

import numpy
X = numpy.random.randint(0, 10, size=10)
print(X)

输出:

[4 8 0 4 9 6 9 9 0 7]

Generating random integers between 0 and 9.

import numpy
X = numpy.random.randint(0, 10, size=10)
print(X)

Output:

[4 8 0 4 9 6 9 9 0 7]
你げ笑在眉眼 2024-10-05 07:43:47

最好的方法是使用 import Random 函数

import random
print(random.sample(range(10), 10))

或不导入任何库:

n={} 
for i in range(10):
    n[i]=i

for p in range(10):
    print(n.popitem()[1])

这里 popitems 从字典n 中删除并返回任意值。

Best way is to use import Random function

import random
print(random.sample(range(10), 10))

or without any library import:

n={} 
for i in range(10):
    n[i]=i

for p in range(10):
    print(n.popitem()[1])

here the popitems removes and returns an arbitrary value from the dictionary n.

东京女 2024-10-05 07:43:47

random.sample 是另一个可以使用的

import random
n = 1 # specify the no. of numbers
num = random.sample(range(10),  n)
num[0] # is the required number

random.sample is another that can be used

import random
n = 1 # specify the no. of numbers
num = random.sample(range(10),  n)
num[0] # is the required number
月棠 2024-10-05 07:43:47

这更像是一种数学方法,但它 100% 有效:

假设您想使用 random.random() 函数生成 aa 之间的数字。代码>b。要实现此目的,只需执行以下操作:

num = (ba)*random.random() + a;

当然,您可以生成更多数字。

This is more of a mathematical approach but it works 100% of the time:

Let's say you want to use random.random() function to generate a number between a and b. To achieve this, just do the following:

num = (b-a)*random.random() + a;

Of course, you can generate more numbers.

娇妻 2024-10-05 07:43:47

random 模块的文档页面:

警告:该模块的伪随机生成器不应该
用于安全目的。如果您需要,请使用 os.urandom() 或 SystemRandom
需要一个加密安全的伪随机数生成器。

random.SystemRandom,在Python 2.4 被认为是加密安全。它在撰写本文时最新的 Python 3.7.1 中仍然可用。

>>> import string
>>> string.digits
'0123456789'
>>> import random
>>> random.SystemRandom().choice(string.digits)
'8'
>>> random.SystemRandom().choice(string.digits)
'1'
>>> random.SystemRandom().choice(string.digits)
'8'
>>> random.SystemRandom().choice(string.digits)
'5'

除了 string.digits 之外,还可以使用 range 来代替其他一些答案,或许还可以进行理解。根据您的需要混合搭配。

From the documentation page for the random module:

Warning: The pseudo-random generators of this module should not be
used for security purposes. Use os.urandom() or SystemRandom if you
require a cryptographically secure pseudo-random number generator.

random.SystemRandom, which was introduced in Python 2.4, is considered cryptographically secure. It is still available in Python 3.7.1 which is current at time of writing.

>>> import string
>>> string.digits
'0123456789'
>>> import random
>>> random.SystemRandom().choice(string.digits)
'8'
>>> random.SystemRandom().choice(string.digits)
'1'
>>> random.SystemRandom().choice(string.digits)
'8'
>>> random.SystemRandom().choice(string.digits)
'5'

Instead of string.digits, range could be used per some of the other answers along perhaps with a comprehension. Mix and match according to your needs.

迷路的信 2024-10-05 07:43:47

我想我应该用 quantumrand 添加这些答案,它使用 ANU 的量子数生成器。不幸的是,这需要互联网连接,但如果您关心数字的“随机性”,那么这可能很有用。

https://pypi.org/project/quantumrand/

示例

import quantumrand

number = quantumrand.randint(0, 9)

print(number)

输出:4

文档有很多不同的示例,包括掷骰子和列表选择器。

I thought I'd add to these answers with quantumrand, which uses ANU's quantum number generator. Unfortunately this requires an internet connection, but if you're concerned with "how random" the numbers are then this could be useful.

https://pypi.org/project/quantumrand/

Example

import quantumrand

number = quantumrand.randint(0, 9)

print(number)

Output: 4

The docs have a lot of different examples including dice rolls and a list picker.

节枝 2024-10-05 07:43:47

对于 Python 3.6,我的运气更好,

str_Key = ""                                                                                                
str_RandomKey = ""                                                                                          
for int_I in range(128):                                                                                    
      str_Key = random.choice('0123456789')
      str_RandomKey = str_RandomKey + str_Key 

只需添加 'ABCD' 和 'abcd' 或 '^!~=-><' 等字符要更改要从中提取的字符池,请更改范围以更改生成的字符数。

I had better luck with this for Python 3.6

str_Key = ""                                                                                                
str_RandomKey = ""                                                                                          
for int_I in range(128):                                                                                    
      str_Key = random.choice('0123456789')
      str_RandomKey = str_RandomKey + str_Key 

Just add characters like 'ABCD' and 'abcd' or '^!~=-><' to alter the character pool to pull from, change the range to alter the number of characters generated.

一生独一 2024-10-05 07:43:47

OpenTURNS 不仅允许模拟随机整数,还可以使用 UserDefined 定义的类来定义关联的分布。

下面模拟了 12 个分布结果。

import openturns as ot
points = [[i] for i in range(10)]
distribution = ot.UserDefined(points) # By default, with equal weights.
for i in range(12):
    x = distribution.getRealization()
    print(i,x)

打印结果:

0 [8]
1 [7]
2 [4]
3 [7]
4 [3]
5 [3]
6 [2]
7 [9]
8 [0]
9 [5]
10 [9]
11 [6]

括号之所以存在,是因为x是一维中的Point
在一次调用 getSample 中生成 12 个结果会更容易:

sample = distribution.getSample(12)

将产生:

>>> print(sample)
     [ v0 ]
 0 : [ 3  ]
 1 : [ 9  ]
 2 : [ 6  ]
 3 : [ 3  ]
 4 : [ 2  ]
 5 : [ 6  ]
 6 : [ 9  ]
 7 : [ 5  ]
 8 : [ 9  ]
 9 : [ 5  ]
10 : [ 3  ]
11 : [ 2  ]

有关此主题的更多详细信息如下:http://openturns.github.io/openturns/master/user_manual/_ generated/openturns.UserDefined.html

OpenTURNS allows to not only simulate the random integers but also to define the associated distribution with the UserDefined defined class.

The following simulates 12 outcomes of the distribution.

import openturns as ot
points = [[i] for i in range(10)]
distribution = ot.UserDefined(points) # By default, with equal weights.
for i in range(12):
    x = distribution.getRealization()
    print(i,x)

This prints:

0 [8]
1 [7]
2 [4]
3 [7]
4 [3]
5 [3]
6 [2]
7 [9]
8 [0]
9 [5]
10 [9]
11 [6]

The brackets are there becausex is a Point in 1-dimension.
It would be easier to generate the 12 outcomes in a single call to getSample:

sample = distribution.getSample(12)

would produce:

>>> print(sample)
     [ v0 ]
 0 : [ 3  ]
 1 : [ 9  ]
 2 : [ 6  ]
 3 : [ 3  ]
 4 : [ 2  ]
 5 : [ 6  ]
 6 : [ 9  ]
 7 : [ 5  ]
 8 : [ 9  ]
 9 : [ 5  ]
10 : [ 3  ]
11 : [ 2  ]

More details on this topic are here: http://openturns.github.io/openturns/master/user_manual/_generated/openturns.UserDefined.html

笑梦风尘 2024-10-05 07:43:47

生成 0 到 9 之间的随机整数

使用 numpy

如果您可以接受 numpy 依赖项,那么从版本 1.17 开始,numpy 具有 生成器,如果你想的话,它比 randint/choice 等快得多生成很多随机整数(例如超过10000个整数)。要构造它,请使用np.random.default_rng()。然后,要生成随机整数,请调用 integers()choice()。如果要生成大量随机数列表(例如生成 100 万个随机整数,numpy 生成器比 numpy 的 randint 快约 3 倍,约快 40 倍),它比标准库快得多比 stdlib 的随机1)。

例如,要生成 100 万个 0 到 9 之间的整数,可以使用以下任一方法。

import numpy as np
# option 1
numbers = np.random.default_rng().integers(0, 10, size=1000000)
# option 2
numbers = np.random.default_rng().choice(10, size=1000000)

默认使用PCG64生成器;但是,如果您想使用标准库中随机使用的 Mersenne Twister 生成器,那么您可以将其实例作为种子序列传递给 default_rng() ,如下所示接下来。

rng = np.random.default_rng(np.random.MT19937())
numbers = rng.integers(0, 10, size=1000)

使用 random

如果您仅限于标准库,并且想要生成大量随机整数,那么 random.choices()快得多random.randint()random.randrange().2 例如,生成 0 到 9 之间的 100 万个随机整数:

import random
numbers = random.choices(range(10), k=1000000)

一些计时结果1

在 Python 3.12 和 numpy 1.26 上测试。

import timeit
import random
import numpy as np

def numpy_randint():
    return np.random.randint(0, 10, size=1000000)

def numpy_Gen_integers():
    return np.random.default_rng().integers(0, 10, size=1000000)

def numpy_Gen_choice():
    return np.random.default_rng().choice(10, size=1000000)

def random_randrange():
    return [random.randrange(10) for _ in range(1000000)]

def random_choices():
    return random.choices(range(10), k=1000000)


t1 = min(timeit.repeat(numpy_randint, number=100))      # 1.9559144999366254
t2 = min(timeit.repeat(numpy_Gen_integers, number=100)) # 0.6704635999631137
t3 = min(timeit.repeat(numpy_Gen_choice, number=100))   # 0.6696784000378102
t4 = min(timeit.repeat(random_randrange, number=100))   # 64.98768060002476
t5 = min(timeit.repeat(random_choices, number=100))     # 25.686857299879193

2 如果我们查看它们的源实现,random.randrange()(和 random.randint() 因为它是前者的语法糖)使用 while 循环生成伪-随机数通过_randbelow 方法,而 random.choices() 调用 random() 一次并将其用于 对总体进行索引。因此,如果需要生成大量伪随机数,则该 while 循环的成本就会增加。

Generate random integers between 0 and 9

With numpy

If you're OK with having a numpy dependency, then since version 1.17, numpy has Generators, which are much faster than randint/choice etc. if you want to generate a lot of random integers (e.g. more than 10000 integers). To construct it, use np.random.default_rng(). Then to generate random integers, call integers() or choice(). It is much faster than the standard library if you want to generate a large list of random numbers (e.g. to generate 1 million random integers, numpy generators are about 3 times faster than numpy's randint and about 40 times faster than stdlib's random1).

For example, to generate 1 million integers between 0 and 9, either of the following could be used.

import numpy as np
# option 1
numbers = np.random.default_rng().integers(0, 10, size=1000000)
# option 2
numbers = np.random.default_rng().choice(10, size=1000000)

By default, it uses PCG64 generator; however, if you want to use the Mersenne Twister generator which is used in random in the standard library, then you could pass its instance as a seeding sequence to default_rng() as follows.

rng = np.random.default_rng(np.random.MT19937())
numbers = rng.integers(0, 10, size=1000)

With random

If you're restricted to the standard library, and you want to generate a lot of random integers, then random.choices() is much faster than random.randint() or random.randrange().2 For example to generate 1 million random integers between 0 and 9:

import random
numbers = random.choices(range(10), k=1000000)

Some timing results1

Tested on Python 3.12 and numpy 1.26.

import timeit
import random
import numpy as np

def numpy_randint():
    return np.random.randint(0, 10, size=1000000)

def numpy_Gen_integers():
    return np.random.default_rng().integers(0, 10, size=1000000)

def numpy_Gen_choice():
    return np.random.default_rng().choice(10, size=1000000)

def random_randrange():
    return [random.randrange(10) for _ in range(1000000)]

def random_choices():
    return random.choices(range(10), k=1000000)


t1 = min(timeit.repeat(numpy_randint, number=100))      # 1.9559144999366254
t2 = min(timeit.repeat(numpy_Gen_integers, number=100)) # 0.6704635999631137
t3 = min(timeit.repeat(numpy_Gen_choice, number=100))   # 0.6696784000378102
t4 = min(timeit.repeat(random_randrange, number=100))   # 64.98768060002476
t5 = min(timeit.repeat(random_choices, number=100))     # 25.686857299879193

2 If we look at their source implementations, random.randrange() (and random.randint() because it is the former's syntactic sugar) use a while-loop to generate a pseudo-random number via _randbelow method while random.choices() calls random() once and uses it to index the population. So if a lot of pseudo-random numbers need to be generated, the cost of this while-loop adds up.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文