Hướng dẫn random number generator from scratch python - trình tạo số ngẫu nhiên từ python đầu

Permalink

bậc thầy

Chuyển nhánh/thẻ

Không thể tải các nhánh

Không có gì để hiển thị

{{refname}}

Tên đã được sử dụng

Một thẻ đã tồn tại với tên chi nhánh được cung cấp. Nhiều lệnh GIT chấp nhận cả tên thẻ và tên chi nhánh, vì vậy việc tạo nhánh này có thể gây ra hành vi bất ngờ. Bạn có chắc là bạn muốn tạo chi nhánh này?

Đi nộp

  • Đi nộp
  • Sao chép đường dẫn
  • Sao chép permalink

Không thể lấy lại những người đóng góp tại thời điểm này

666 dòng [666 SLOC] 117 KB 117 KB

Đổ lỗi

Mở trong máy tính để bàn GitHub

  • Mở với máy tính để bàn
  • Xem thô
  • Xem đổ lỗi

Xin lỗi, có lỗi xảy ra. Tải lại?

Xin lỗi, chúng tôi không thể hiển thị tệp này.

Xin lỗi, tệp này không hợp lệ nên nó không thể được hiển thị.

Để tạo số ngẫu nhiên trong Python, hàm

5
2 được sử dụng. Hàm này được xác định trong mô -đun ngẫu nhiên.

Mã nguồn

# Program to generate a random number between 0 and 9

# importing the random module
import random

print[random.randint[0,9]]

Đầu ra

5

Lưu ý rằng chúng tôi có thể nhận được đầu ra khác nhau vì chương trình này tạo ra số ngẫu nhiên & nbsp; trong phạm vi 0 và 9. & nbsp; cú pháp của hàm này là:

random.randint[a,b]

Điều này trả về một số N trong phạm vi bao gồm

5
3, có nghĩa là
5
4, trong đó các điểm cuối được đưa vào phạm vi.

Mã nguồn: lib/ngẫu nhiên.py Lib/random.py

Mô-đun này thực hiện các trình tạo số giả giả cho các phân phối khác nhau.

Đối với số nguyên, có lựa chọn thống nhất từ ​​một phạm vi. Đối với các chuỗi, có sự lựa chọn thống nhất của một phần tử ngẫu nhiên, một hàm để tạo ra một hoán vị ngẫu nhiên của một danh sách tại chỗ và một hàm để lấy mẫu ngẫu nhiên mà không cần thay thế.

Trên dòng thực, có các hàm để tính toán đồng nhất, bình thường [Gaussian], phân phối theo cấp số nhân, gamma và beta âm. Để tạo phân phối các góc, phân phối von Mises có sẵn.

Hầu như tất cả các hàm mô-đun phụ thuộc vào hàm cơ bản

5
5, tạo ra một phao ngẫu nhiên đồng đều trong phạm vi bán mở [0,0, 1.0]. Python sử dụng Mersenne Twister làm trình tạo cốt lõi. Nó tạo ra phao chính xác 53 bit và có thời gian 2 ** 19937-1. Việc triển khai cơ bản trong C là cả nhanh và sleadSafe. Mersenne Twister là một trong những bộ tạo số ngẫu nhiên được thử nghiệm rộng rãi nhất đang tồn tại. Tuy nhiên, hoàn toàn quyết định, nó không phù hợp cho tất cả các mục đích và hoàn toàn không phù hợp cho mục đích mật mã.

Các chức năng được cung cấp bởi mô -đun này thực sự là các phương thức ràng buộc của một trường hợp ẩn của lớp

5
6. Bạn có thể khởi tạo các trường hợp của riêng bạn là
5
7 để có được các trình tạo mà không chia sẻ trạng thái.

Lớp

5
7 cũng có thể được phân nhóm nếu bạn muốn sử dụng một trình tạo cơ bản khác của sự phát minh của riêng bạn: trong trường hợp đó, ghi đè các phương thức
5
5,
random.randint[a,b]
0,
random.randint[a,b]
1 và
random.randint[a,b]
2. Tùy chọn, một trình tạo mới có thể cung cấp một phương thức
random.randint[a,b]
3 - điều này cho phép
random.randint[a,b]
4 tạo ra các lựa chọn trên một phạm vi lớn tùy ý.

Mô -đun

random.randint[a,b]
5 cũng cung cấp lớp
random.randint[a,b]
6 sử dụng hàm hệ thống
random.randint[a,b]
7 để tạo số ngẫu nhiên từ các nguồn được cung cấp bởi hệ điều hành.

Cảnh báo

Không nên sử dụng các trình tạo giả ngẫu nhiên của mô-đun này cho mục đích bảo mật. Để sử dụng bảo mật hoặc sử dụng mật mã, hãy xem mô -đun

random.randint[a,b]
8.

Xem thêm

M. Matsumoto và T. Nishimura, Hồi Mersenne Twister: Một trình tạo số giả đồng nhất cách đồng nhất 623 chiều, Giao dịch ACM về mô hình hóa và mô phỏng máy tính Vol. 8, Số 1, tháng 1 Trang 3 Điện30 1998.

Công thức bổ sung-đa dạng-với-carry cho một trình tạo số ngẫu nhiên thay thế tương thích với một thời gian dài và các hoạt động cập nhật tương đối đơn giản.

Chức năng kế toán

ngẫu nhiên.seed [a = none, phiên bản = 2] ¶seed[a=None, version=2]

Khởi tạo trình tạo số ngẫu nhiên.

Nếu A bị bỏ qua hoặc

random.randint[a,b]
9, thời gian hệ thống hiện tại được sử dụng. Nếu các nguồn ngẫu nhiên được cung cấp bởi hệ điều hành, chúng được sử dụng thay vì thời gian hệ thống [xem hàm
random.randint[a,b]
7 để biết chi tiết về tính khả dụng].

Nếu A là INT, nó được sử dụng trực tiếp.

Với phiên bản 2 [mặc định], đối tượng

          x ** [alpha - 1] * math.exp[-x / beta]
pdf[x] =  --------------------------------------
            math.gamma[alpha] * beta ** alpha
1,
          x ** [alpha - 1] * math.exp[-x / beta]
pdf[x] =  --------------------------------------
            math.gamma[alpha] * beta ** alpha
2 hoặc
          x ** [alpha - 1] * math.exp[-x / beta]
pdf[x] =  --------------------------------------
            math.gamma[alpha] * beta ** alpha
3 được chuyển đổi thành
          x ** [alpha - 1] * math.exp[-x / beta]
pdf[x] =  --------------------------------------
            math.gamma[alpha] * beta ** alpha
4 và tất cả các bit của nó được sử dụng.

Với phiên bản 1 [được cung cấp để tái tạo các chuỗi ngẫu nhiên từ các phiên bản Python cũ hơn], thuật toán cho

          x ** [alpha - 1] * math.exp[-x / beta]
pdf[x] =  --------------------------------------
            math.gamma[alpha] * beta ** alpha
1 và
          x ** [alpha - 1] * math.exp[-x / beta]
pdf[x] =  --------------------------------------
            math.gamma[alpha] * beta ** alpha
2 tạo ra phạm vi hạt hẹp hơn.

Đã thay đổi trong phiên bản 3.2: Đã chuyển sang sơ đồ phiên bản 2 sử dụng tất cả các bit trong hạt giống.Moved to the version 2 scheme which uses all of the bits in a string seed.

Đã thay đổi trong phiên bản 3.11: Hạt giống phải là một trong các loại sau: Nonetype,

          x ** [alpha - 1] * math.exp[-x / beta]
pdf[x] =  --------------------------------------
            math.gamma[alpha] * beta ** alpha
4,
          x ** [alpha - 1] * math.exp[-x / beta]
pdf[x] =  --------------------------------------
            math.gamma[alpha] * beta ** alpha
8,
          x ** [alpha - 1] * math.exp[-x / beta]
pdf[x] =  --------------------------------------
            math.gamma[alpha] * beta ** alpha
1,
          x ** [alpha - 1] * math.exp[-x / beta]
pdf[x] =  --------------------------------------
            math.gamma[alpha] * beta ** alpha
2 hoặc
          x ** [alpha - 1] * math.exp[-x / beta]
pdf[x] =  --------------------------------------
            math.gamma[alpha] * beta ** alpha
3.The seed must be one of the following types: NoneType,
          x ** [alpha - 1] * math.exp[-x / beta]
pdf[x] =  --------------------------------------
            math.gamma[alpha] * beta ** alpha
4,
          x ** [alpha - 1] * math.exp[-x / beta]
pdf[x] =  --------------------------------------
            math.gamma[alpha] * beta ** alpha
8,
          x ** [alpha - 1] * math.exp[-x / beta]
pdf[x] =  --------------------------------------
            math.gamma[alpha] * beta ** alpha
1,
          x ** [alpha - 1] * math.exp[-x / beta]
pdf[x] =  --------------------------------------
            math.gamma[alpha] * beta ** alpha
2, or
          x ** [alpha - 1] * math.exp[-x / beta]
pdf[x] =  --------------------------------------
            math.gamma[alpha] * beta ** alpha
3.

ngẫu nhiên.getstate [] ¶getstate[]

Trả về một đối tượng chụp trạng thái bên trong hiện tại của trình tạo. Đối tượng này có thể được chuyển sang

random.randint[a,b]
2 để khôi phục trạng thái.

ngẫu nhiên.setstate [trạng thái] ¶setstate[state]

Nhà nước đáng lẽ phải được lấy từ một cuộc gọi trước đó đến

random.randint[a,b]
1 và
random.randint[a,b]
2 khôi phục trạng thái bên trong của trình tạo về những gì nó đã được gọi là
random.randint[a,b]
1 được gọi.

Chức năng cho byte¶

ngẫu nhiên.randbytes [n] ¶randbytes[n]

Tạo n ngẫu nhiên byte.

Phương pháp này không nên được sử dụng để tạo mã thông báo bảo mật. Sử dụng

>>> random[]                             # Random float:  0.0 >> uniform[2.5, 10.0]                   # Random float:  2.5 > expovariate[1 / 5]                   # Interval between arrivals averaging 5 seconds
5.148957571865031

>>> randrange[10]                        # Integer from 0 to 9 inclusive
7

>>> randrange[0, 101, 2]                 # Even integer from 0 to 100 inclusive
26

>>> choice[['win', 'lose', 'draw']]      # Single random element from a sequence
'draw'

>>> deck = 'ace two three four'.split[]
>>> shuffle[deck]                        # Shuffle a list
>>> deck
['four', 'two', 'ace', 'three']

>>> sample[[10, 20, 30, 40, 50], k=4]    # Four samples without replacement
[40, 10, 50, 30]
6 thay thế.

Mới trong phiên bản 3.9.

Chức năng cho số nguyên

ngẫu nhiên.randrange [dừng] ¶ ngẫu nhiên.randrange [bắt đầu, dừng [, bước]]randrange[stop]random.randrange[start, stop[, step]]

Trả về một phần tử được chọn ngẫu nhiên từ

>>> random[]                             # Random float:  0.0 >> uniform[2.5, 10.0]                   # Random float:  2.5 > expovariate[1 / 5]                   # Interval between arrivals averaging 5 seconds
5.148957571865031

>>> randrange[10]                        # Integer from 0 to 9 inclusive
7

>>> randrange[0, 101, 2]                 # Even integer from 0 to 100 inclusive
26

>>> choice[['win', 'lose', 'draw']]      # Single random element from a sequence
'draw'

>>> deck = 'ace two three four'.split[]
>>> shuffle[deck]                        # Shuffle a list
>>> deck
['four', 'two', 'ace', 'three']

>>> sample[[10, 20, 30, 40, 50], k=4]    # Four samples without replacement
[40, 10, 50, 30]
7. Điều này tương đương với
>>> random[]                             # Random float:  0.0 >> uniform[2.5, 10.0]                   # Random float:  2.5 > expovariate[1 / 5]                   # Interval between arrivals averaging 5 seconds
5.148957571865031

>>> randrange[10]                        # Integer from 0 to 9 inclusive
7

>>> randrange[0, 101, 2]                 # Even integer from 0 to 100 inclusive
26

>>> choice[['win', 'lose', 'draw']]      # Single random element from a sequence
'draw'

>>> deck = 'ace two three four'.split[]
>>> shuffle[deck]                        # Shuffle a list
>>> deck
['four', 'two', 'ace', 'three']

>>> sample[[10, 20, 30, 40, 50], k=4]    # Four samples without replacement
[40, 10, 50, 30]
8, nhưng không thực sự xây dựng một đối tượng phạm vi.

Các mẫu đối số vị trí phù hợp với

>>> random[]                             # Random float:  0.0 >> uniform[2.5, 10.0]                   # Random float:  2.5 > expovariate[1 / 5]                   # Interval between arrivals averaging 5 seconds
5.148957571865031

>>> randrange[10]                        # Integer from 0 to 9 inclusive
7

>>> randrange[0, 101, 2]                 # Even integer from 0 to 100 inclusive
26

>>> choice[['win', 'lose', 'draw']]      # Single random element from a sequence
'draw'

>>> deck = 'ace two three four'.split[]
>>> shuffle[deck]                        # Shuffle a list
>>> deck
['four', 'two', 'ace', 'three']

>>> sample[[10, 20, 30, 40, 50], k=4]    # Four samples without replacement
[40, 10, 50, 30]
9. Không nên sử dụng đối số từ khóa vì hàm có thể sử dụng chúng theo những cách không mong muốn.

Đã thay đổi trong phiên bản 3.2:

random.randint[a,b]
4 tinh vi hơn về việc tạo ra các giá trị phân phối đều nhau. Trước đây, nó đã sử dụng một phong cách như
>>> # Six roulette wheel spins [weighted sampling with replacement]
>>> choices[['red', 'black', 'green'], [18, 18, 2], k=6]
['red', 'green', 'black', 'black', 'red', 'black']

>>> # Deal 20 cards without replacement from a deck
>>> # of 52 playing cards, and determine the proportion of cards
>>> # with a ten-value:  ten, jack, queen, or king.
>>> dealt = sample[['tens', 'low cards'], counts=[16, 36], k=20]
>>> dealt.count['tens'] / 20
0.15

>>> # Estimate the probability of getting 5 or more heads from 7 spins
>>> # of a biased coin that settles on heads 60% of the time.
>>> def trial[]:
...     return choices['HT', cum_weights=[0.60, 1.00], k=7].count['H'] >= 5
...
>>> sum[trial[] for i in range[10_000]] / 10_000
0.4169

>>> # Probability of the median of 5 samples being in middle two quartiles
>>> def trial[]:
...     return 2_500 > sum[trial[] for i in range[10_000]] / 10_000
0.7958
1 có thể tạo ra các phân phối hơi không đồng đều.
random.randint[a,b]
4 is more sophisticated about producing equally distributed values. Formerly it used a style like
>>> # Six roulette wheel spins [weighted sampling with replacement]
>>> choices[['red', 'black', 'green'], [18, 18, 2], k=6]
['red', 'green', 'black', 'black', 'red', 'black']

>>> # Deal 20 cards without replacement from a deck
>>> # of 52 playing cards, and determine the proportion of cards
>>> # with a ten-value:  ten, jack, queen, or king.
>>> dealt = sample[['tens', 'low cards'], counts=[16, 36], k=20]
>>> dealt.count['tens'] / 20
0.15

>>> # Estimate the probability of getting 5 or more heads from 7 spins
>>> # of a biased coin that settles on heads 60% of the time.
>>> def trial[]:
...     return choices['HT', cum_weights=[0.60, 1.00], k=7].count['H'] >= 5
...
>>> sum[trial[] for i in range[10_000]] / 10_000
0.4169

>>> # Probability of the median of 5 samples being in middle two quartiles
>>> def trial[]:
...     return 2_500 > sum[trial[] for i in range[10_000]] / 10_000
0.7958
1 which could produce slightly uneven distributions.

Không dùng nữa kể từ phiên bản 3.10: Chuyển đổi tự động các loại không nguyên thành các số nguyên tương đương được không dùng nữa. Hiện tại

>>> # Six roulette wheel spins [weighted sampling with replacement]
>>> choices[['red', 'black', 'green'], [18, 18, 2], k=6]
['red', 'green', 'black', 'black', 'red', 'black']

>>> # Deal 20 cards without replacement from a deck
>>> # of 52 playing cards, and determine the proportion of cards
>>> # with a ten-value:  ten, jack, queen, or king.
>>> dealt = sample[['tens', 'low cards'], counts=[16, 36], k=20]
>>> dealt.count['tens'] / 20
0.15

>>> # Estimate the probability of getting 5 or more heads from 7 spins
>>> # of a biased coin that settles on heads 60% of the time.
>>> def trial[]:
...     return choices['HT', cum_weights=[0.60, 1.00], k=7].count['H'] >= 5
...
>>> sum[trial[] for i in range[10_000]] / 10_000
0.4169

>>> # Probability of the median of 5 samples being in middle two quartiles
>>> def trial[]:
...     return 2_500 > sum[trial[] for i in range[10_000]] / 10_000
0.7958
2 được chuyển đổi không mất khỏi
>>> # Six roulette wheel spins [weighted sampling with replacement]
>>> choices[['red', 'black', 'green'], [18, 18, 2], k=6]
['red', 'green', 'black', 'black', 'red', 'black']

>>> # Deal 20 cards without replacement from a deck
>>> # of 52 playing cards, and determine the proportion of cards
>>> # with a ten-value:  ten, jack, queen, or king.
>>> dealt = sample[['tens', 'low cards'], counts=[16, 36], k=20]
>>> dealt.count['tens'] / 20
0.15

>>> # Estimate the probability of getting 5 or more heads from 7 spins
>>> # of a biased coin that settles on heads 60% of the time.
>>> def trial[]:
...     return choices['HT', cum_weights=[0.60, 1.00], k=7].count['H'] >= 5
...
>>> sum[trial[] for i in range[10_000]] / 10_000
0.4169

>>> # Probability of the median of 5 samples being in middle two quartiles
>>> def trial[]:
...     return 2_500 > sum[trial[] for i in range[10_000]] / 10_000
0.7958
3. Trong tương lai, điều này sẽ tăng
>>> # Six roulette wheel spins [weighted sampling with replacement]
>>> choices[['red', 'black', 'green'], [18, 18, 2], k=6]
['red', 'green', 'black', 'black', 'red', 'black']

>>> # Deal 20 cards without replacement from a deck
>>> # of 52 playing cards, and determine the proportion of cards
>>> # with a ten-value:  ten, jack, queen, or king.
>>> dealt = sample[['tens', 'low cards'], counts=[16, 36], k=20]
>>> dealt.count['tens'] / 20
0.15

>>> # Estimate the probability of getting 5 or more heads from 7 spins
>>> # of a biased coin that settles on heads 60% of the time.
>>> def trial[]:
...     return choices['HT', cum_weights=[0.60, 1.00], k=7].count['H'] >= 5
...
>>> sum[trial[] for i in range[10_000]] / 10_000
0.4169

>>> # Probability of the median of 5 samples being in middle two quartiles
>>> def trial[]:
...     return 2_500 > sum[trial[] for i in range[10_000]] / 10_000
0.7958
4.The automatic conversion of non-integer types to equivalent integers is deprecated. Currently
>>> # Six roulette wheel spins [weighted sampling with replacement]
>>> choices[['red', 'black', 'green'], [18, 18, 2], k=6]
['red', 'green', 'black', 'black', 'red', 'black']

>>> # Deal 20 cards without replacement from a deck
>>> # of 52 playing cards, and determine the proportion of cards
>>> # with a ten-value:  ten, jack, queen, or king.
>>> dealt = sample[['tens', 'low cards'], counts=[16, 36], k=20]
>>> dealt.count['tens'] / 20
0.15

>>> # Estimate the probability of getting 5 or more heads from 7 spins
>>> # of a biased coin that settles on heads 60% of the time.
>>> def trial[]:
...     return choices['HT', cum_weights=[0.60, 1.00], k=7].count['H'] >= 5
...
>>> sum[trial[] for i in range[10_000]] / 10_000
0.4169

>>> # Probability of the median of 5 samples being in middle two quartiles
>>> def trial[]:
...     return 2_500 > sum[trial[] for i in range[10_000]] / 10_000
0.7958
2 is losslessly converted to
>>> # Six roulette wheel spins [weighted sampling with replacement]
>>> choices[['red', 'black', 'green'], [18, 18, 2], k=6]
['red', 'green', 'black', 'black', 'red', 'black']

>>> # Deal 20 cards without replacement from a deck
>>> # of 52 playing cards, and determine the proportion of cards
>>> # with a ten-value:  ten, jack, queen, or king.
>>> dealt = sample[['tens', 'low cards'], counts=[16, 36], k=20]
>>> dealt.count['tens'] / 20
0.15

>>> # Estimate the probability of getting 5 or more heads from 7 spins
>>> # of a biased coin that settles on heads 60% of the time.
>>> def trial[]:
...     return choices['HT', cum_weights=[0.60, 1.00], k=7].count['H'] >= 5
...
>>> sum[trial[] for i in range[10_000]] / 10_000
0.4169

>>> # Probability of the median of 5 samples being in middle two quartiles
>>> def trial[]:
...     return 2_500 > sum[trial[] for i in range[10_000]] / 10_000
0.7958
3. In the future, this will raise a
>>> # Six roulette wheel spins [weighted sampling with replacement]
>>> choices[['red', 'black', 'green'], [18, 18, 2], k=6]
['red', 'green', 'black', 'black', 'red', 'black']

>>> # Deal 20 cards without replacement from a deck
>>> # of 52 playing cards, and determine the proportion of cards
>>> # with a ten-value:  ten, jack, queen, or king.
>>> dealt = sample[['tens', 'low cards'], counts=[16, 36], k=20]
>>> dealt.count['tens'] / 20
0.15

>>> # Estimate the probability of getting 5 or more heads from 7 spins
>>> # of a biased coin that settles on heads 60% of the time.
>>> def trial[]:
...     return choices['HT', cum_weights=[0.60, 1.00], k=7].count['H'] >= 5
...
>>> sum[trial[] for i in range[10_000]] / 10_000
0.4169

>>> # Probability of the median of 5 samples being in middle two quartiles
>>> def trial[]:
...     return 2_500 > sum[trial[] for i in range[10_000]] / 10_000
0.7958
4.

Không dùng nữa kể từ phiên bản 3.10: Ngoại lệ được nâng lên đối với các giá trị không tích hợp như

>>> # Six roulette wheel spins [weighted sampling with replacement]
>>> choices[['red', 'black', 'green'], [18, 18, 2], k=6]
['red', 'green', 'black', 'black', 'red', 'black']

>>> # Deal 20 cards without replacement from a deck
>>> # of 52 playing cards, and determine the proportion of cards
>>> # with a ten-value:  ten, jack, queen, or king.
>>> dealt = sample[['tens', 'low cards'], counts=[16, 36], k=20]
>>> dealt.count['tens'] / 20
0.15

>>> # Estimate the probability of getting 5 or more heads from 7 spins
>>> # of a biased coin that settles on heads 60% of the time.
>>> def trial[]:
...     return choices['HT', cum_weights=[0.60, 1.00], k=7].count['H'] >= 5
...
>>> sum[trial[] for i in range[10_000]] / 10_000
0.4169

>>> # Probability of the median of 5 samples being in middle two quartiles
>>> def trial[]:
...     return 2_500 > sum[trial[] for i in range[10_000]] / 10_000
0.7958
5 hoặc
>>> # Six roulette wheel spins [weighted sampling with replacement]
>>> choices[['red', 'black', 'green'], [18, 18, 2], k=6]
['red', 'green', 'black', 'black', 'red', 'black']

>>> # Deal 20 cards without replacement from a deck
>>> # of 52 playing cards, and determine the proportion of cards
>>> # with a ten-value:  ten, jack, queen, or king.
>>> dealt = sample[['tens', 'low cards'], counts=[16, 36], k=20]
>>> dealt.count['tens'] / 20
0.15

>>> # Estimate the probability of getting 5 or more heads from 7 spins
>>> # of a biased coin that settles on heads 60% of the time.
>>> def trial[]:
...     return choices['HT', cum_weights=[0.60, 1.00], k=7].count['H'] >= 5
...
>>> sum[trial[] for i in range[10_000]] / 10_000
0.4169

>>> # Probability of the median of 5 samples being in middle two quartiles
>>> def trial[]:
...     return 2_500 > sum[trial[] for i in range[10_000]] / 10_000
0.7958
6 sẽ được thay đổi từ
>>> # Six roulette wheel spins [weighted sampling with replacement]
>>> choices[['red', 'black', 'green'], [18, 18, 2], k=6]
['red', 'green', 'black', 'black', 'red', 'black']

>>> # Deal 20 cards without replacement from a deck
>>> # of 52 playing cards, and determine the proportion of cards
>>> # with a ten-value:  ten, jack, queen, or king.
>>> dealt = sample[['tens', 'low cards'], counts=[16, 36], k=20]
>>> dealt.count['tens'] / 20
0.15

>>> # Estimate the probability of getting 5 or more heads from 7 spins
>>> # of a biased coin that settles on heads 60% of the time.
>>> def trial[]:
...     return choices['HT', cum_weights=[0.60, 1.00], k=7].count['H'] >= 5
...
>>> sum[trial[] for i in range[10_000]] / 10_000
0.4169

>>> # Probability of the median of 5 samples being in middle two quartiles
>>> def trial[]:
...     return 2_500 > sum[trial[] for i in range[10_000]] / 10_000
0.7958
7 thành
>>> # Six roulette wheel spins [weighted sampling with replacement]
>>> choices[['red', 'black', 'green'], [18, 18, 2], k=6]
['red', 'green', 'black', 'black', 'red', 'black']

>>> # Deal 20 cards without replacement from a deck
>>> # of 52 playing cards, and determine the proportion of cards
>>> # with a ten-value:  ten, jack, queen, or king.
>>> dealt = sample[['tens', 'low cards'], counts=[16, 36], k=20]
>>> dealt.count['tens'] / 20
0.15

>>> # Estimate the probability of getting 5 or more heads from 7 spins
>>> # of a biased coin that settles on heads 60% of the time.
>>> def trial[]:
...     return choices['HT', cum_weights=[0.60, 1.00], k=7].count['H'] >= 5
...
>>> sum[trial[] for i in range[10_000]] / 10_000
0.4169

>>> # Probability of the median of 5 samples being in middle two quartiles
>>> def trial[]:
...     return 2_500 > sum[trial[] for i in range[10_000]] / 10_000
0.7958
4.The exception raised for non-integral values such as
>>> # Six roulette wheel spins [weighted sampling with replacement]
>>> choices[['red', 'black', 'green'], [18, 18, 2], k=6]
['red', 'green', 'black', 'black', 'red', 'black']

>>> # Deal 20 cards without replacement from a deck
>>> # of 52 playing cards, and determine the proportion of cards
>>> # with a ten-value:  ten, jack, queen, or king.
>>> dealt = sample[['tens', 'low cards'], counts=[16, 36], k=20]
>>> dealt.count['tens'] / 20
0.15

>>> # Estimate the probability of getting 5 or more heads from 7 spins
>>> # of a biased coin that settles on heads 60% of the time.
>>> def trial[]:
...     return choices['HT', cum_weights=[0.60, 1.00], k=7].count['H'] >= 5
...
>>> sum[trial[] for i in range[10_000]] / 10_000
0.4169

>>> # Probability of the median of 5 samples being in middle two quartiles
>>> def trial[]:
...     return 2_500 > sum[trial[] for i in range[10_000]] / 10_000
0.7958
5 or
>>> # Six roulette wheel spins [weighted sampling with replacement]
>>> choices[['red', 'black', 'green'], [18, 18, 2], k=6]
['red', 'green', 'black', 'black', 'red', 'black']

>>> # Deal 20 cards without replacement from a deck
>>> # of 52 playing cards, and determine the proportion of cards
>>> # with a ten-value:  ten, jack, queen, or king.
>>> dealt = sample[['tens', 'low cards'], counts=[16, 36], k=20]
>>> dealt.count['tens'] / 20
0.15

>>> # Estimate the probability of getting 5 or more heads from 7 spins
>>> # of a biased coin that settles on heads 60% of the time.
>>> def trial[]:
...     return choices['HT', cum_weights=[0.60, 1.00], k=7].count['H'] >= 5
...
>>> sum[trial[] for i in range[10_000]] / 10_000
0.4169

>>> # Probability of the median of 5 samples being in middle two quartiles
>>> def trial[]:
...     return 2_500 > sum[trial[] for i in range[10_000]] / 10_000
0.7958
6 will be changed from
>>> # Six roulette wheel spins [weighted sampling with replacement]
>>> choices[['red', 'black', 'green'], [18, 18, 2], k=6]
['red', 'green', 'black', 'black', 'red', 'black']

>>> # Deal 20 cards without replacement from a deck
>>> # of 52 playing cards, and determine the proportion of cards
>>> # with a ten-value:  ten, jack, queen, or king.
>>> dealt = sample[['tens', 'low cards'], counts=[16, 36], k=20]
>>> dealt.count['tens'] / 20
0.15

>>> # Estimate the probability of getting 5 or more heads from 7 spins
>>> # of a biased coin that settles on heads 60% of the time.
>>> def trial[]:
...     return choices['HT', cum_weights=[0.60, 1.00], k=7].count['H'] >= 5
...
>>> sum[trial[] for i in range[10_000]] / 10_000
0.4169

>>> # Probability of the median of 5 samples being in middle two quartiles
>>> def trial[]:
...     return 2_500 > sum[trial[] for i in range[10_000]] / 10_000
0.7958
7 to
>>> # Six roulette wheel spins [weighted sampling with replacement]
>>> choices[['red', 'black', 'green'], [18, 18, 2], k=6]
['red', 'green', 'black', 'black', 'red', 'black']

>>> # Deal 20 cards without replacement from a deck
>>> # of 52 playing cards, and determine the proportion of cards
>>> # with a ten-value:  ten, jack, queen, or king.
>>> dealt = sample[['tens', 'low cards'], counts=[16, 36], k=20]
>>> dealt.count['tens'] / 20
0.15

>>> # Estimate the probability of getting 5 or more heads from 7 spins
>>> # of a biased coin that settles on heads 60% of the time.
>>> def trial[]:
...     return choices['HT', cum_weights=[0.60, 1.00], k=7].count['H'] >= 5
...
>>> sum[trial[] for i in range[10_000]] / 10_000
0.4169

>>> # Probability of the median of 5 samples being in middle two quartiles
>>> def trial[]:
...     return 2_500 > sum[trial[] for i in range[10_000]] / 10_000
0.7958
4.

ngẫu nhiên.randint [a, b] ¶randint[a, b]

Trả về một số nguyên ngẫu nhiên n sao cho

>>> # Six roulette wheel spins [weighted sampling with replacement]
>>> choices[['red', 'black', 'green'], [18, 18, 2], k=6]
['red', 'green', 'black', 'black', 'red', 'black']

>>> # Deal 20 cards without replacement from a deck
>>> # of 52 playing cards, and determine the proportion of cards
>>> # with a ten-value:  ten, jack, queen, or king.
>>> dealt = sample[['tens', 'low cards'], counts=[16, 36], k=20]
>>> dealt.count['tens'] / 20
0.15

>>> # Estimate the probability of getting 5 or more heads from 7 spins
>>> # of a biased coin that settles on heads 60% of the time.
>>> def trial[]:
...     return choices['HT', cum_weights=[0.60, 1.00], k=7].count['H'] >= 5
...
>>> sum[trial[] for i in range[10_000]] / 10_000
0.4169

>>> # Probability of the median of 5 samples being in middle two quartiles
>>> def trial[]:
...     return 2_500 > sum[trial[] for i in range[10_000]] / 10_000
0.7958
9. Bí danh cho
# //www.thoughtco.com/example-of-bootstrapping-3126155
from statistics import fmean as mean
from random import choices

data = [41, 50, 29, 37, 81, 30, 73, 63, 20, 35, 68, 22, 60, 31, 95]
means = sorted[mean[choices[data, k=len[data]]] for i in range[100]]
print[f'The sample mean of {mean[data]:.1f} has a 90% confidence '
      f'interval from {means[5]:.1f} to {means[94]:.1f}']
0.

ngẫu nhiên.getrandbits [k] ¶getrandbits[k]

Trả về một số nguyên python không âm với K BIT ngẫu nhiên. Phương pháp này được cung cấp với Trình tạo Mersennetwister và một số trình tạo khác cũng có thể cung cấp nó như một phần tùy chọn của API. Khi có sẵn,

random.randint[a,b]
3 cho phép
random.randint[a,b]
4 xử lý các phạm vi lớn tùy ý.

Đã thay đổi trong phiên bản 3.9: Phương pháp này hiện không chấp nhận số 0 cho k.This method now accepts zero for k.

Chức năng cho trình tự lor

Random.Choice [SEQ] ¶choice[seq]

Trả về một phần tử ngẫu nhiên từ chuỗi không trống seq. Nếu SEQ trống, tăng

# //www.thoughtco.com/example-of-bootstrapping-3126155
from statistics import fmean as mean
from random import choices

data = [41, 50, 29, 37, 81, 30, 73, 63, 20, 35, 68, 22, 60, 31, 95]
means = sorted[mean[choices[data, k=len[data]]] for i in range[100]]
print[f'The sample mean of {mean[data]:.1f} has a 90% confidence '
      f'interval from {means[5]:.1f} to {means[94]:.1f}']
3.

ngẫu nhiên.choices [dân số, trọng lượng = không, *, cum_weights = none, k = 1] ¶choices[population, weights=None, *, cum_weights=None, k=1]

Trả lại một danh sách kích thước k các yếu tố được chọn từ dân số với sự thay thế. Nếu dân số trống, tăng

# //www.thoughtco.com/example-of-bootstrapping-3126155
from statistics import fmean as mean
from random import choices

data = [41, 50, 29, 37, 81, 30, 73, 63, 20, 35, 68, 22, 60, 31, 95]
means = sorted[mean[choices[data, k=len[data]]] for i in range[100]]
print[f'The sample mean of {mean[data]:.1f} has a 90% confidence '
      f'interval from {means[5]:.1f} to {means[94]:.1f}']
3.

Nếu một chuỗi trọng số được chỉ định, các lựa chọn được thực hiện theo các trọng số tương đối. Ngoài ra, nếu một chuỗi cum_weights được đưa ra, các lựa chọn được thực hiện theo các trọng số tích lũy [có thể được tính toán bằng

# //www.thoughtco.com/example-of-bootstrapping-3126155
from statistics import fmean as mean
from random import choices

data = [41, 50, 29, 37, 81, 30, 73, 63, 20, 35, 68, 22, 60, 31, 95]
means = sorted[mean[choices[data, k=len[data]]] for i in range[100]]
print[f'The sample mean of {mean[data]:.1f} has a 90% confidence '
      f'interval from {means[5]:.1f} to {means[94]:.1f}']
5]. Ví dụ, trọng số tương đối
# //www.thoughtco.com/example-of-bootstrapping-3126155
from statistics import fmean as mean
from random import choices

data = [41, 50, 29, 37, 81, 30, 73, 63, 20, 35, 68, 22, 60, 31, 95]
means = sorted[mean[choices[data, k=len[data]]] for i in range[100]]
print[f'The sample mean of {mean[data]:.1f} has a 90% confidence '
      f'interval from {means[5]:.1f} to {means[94]:.1f}']
6 tương đương với trọng số tích lũy
# //www.thoughtco.com/example-of-bootstrapping-3126155
from statistics import fmean as mean
from random import choices

data = [41, 50, 29, 37, 81, 30, 73, 63, 20, 35, 68, 22, 60, 31, 95]
means = sorted[mean[choices[data, k=len[data]]] for i in range[100]]
print[f'The sample mean of {mean[data]:.1f} has a 90% confidence '
      f'interval from {means[5]:.1f} to {means[94]:.1f}']
7. Trong nội bộ, các trọng số tương đối được chuyển đổi thành trọng số tích lũy trước khi thực hiện các lựa chọn, do đó, việc cung cấp các trọng số tích lũy tiết kiệm công việc.

Nếu không có trọng số và không được chỉ định, các lựa chọn được thực hiện với xác suất bằng nhau. Nếu một chuỗi trọng số được cung cấp, nó phải có cùng chiều dài với trình tự dân số. Đó là một

>>> # Six roulette wheel spins [weighted sampling with replacement]
>>> choices[['red', 'black', 'green'], [18, 18, 2], k=6]
['red', 'green', 'black', 'black', 'red', 'black']

>>> # Deal 20 cards without replacement from a deck
>>> # of 52 playing cards, and determine the proportion of cards
>>> # with a ten-value:  ten, jack, queen, or king.
>>> dealt = sample[['tens', 'low cards'], counts=[16, 36], k=20]
>>> dealt.count['tens'] / 20
0.15

>>> # Estimate the probability of getting 5 or more heads from 7 spins
>>> # of a biased coin that settles on heads 60% of the time.
>>> def trial[]:
...     return choices['HT', cum_weights=[0.60, 1.00], k=7].count['H'] >= 5
...
>>> sum[trial[] for i in range[10_000]] / 10_000
0.4169

>>> # Probability of the median of 5 samples being in middle two quartiles
>>> def trial[]:
...     return 2_500 > sum[trial[] for i in range[10_000]] / 10_000
0.7958
4 để chỉ định cả trọng số và cum_ weights.

Trọng lượng hoặc cum_ weights có thể sử dụng bất kỳ loại số nào tương tác với các giá trị

          x ** [alpha - 1] * math.exp[-x / beta]
pdf[x] =  --------------------------------------
            math.gamma[alpha] * beta ** alpha
8 được trả về bởi
5
5 [bao gồm số nguyên, phao và phân số nhưng không bao gồm số thập phân]. Trọng lượng được coi là không âm và hữu hạn. Một
>>> # Six roulette wheel spins [weighted sampling with replacement]
>>> choices[['red', 'black', 'green'], [18, 18, 2], k=6]
['red', 'green', 'black', 'black', 'red', 'black']

>>> # Deal 20 cards without replacement from a deck
>>> # of 52 playing cards, and determine the proportion of cards
>>> # with a ten-value:  ten, jack, queen, or king.
>>> dealt = sample[['tens', 'low cards'], counts=[16, 36], k=20]
>>> dealt.count['tens'] / 20
0.15

>>> # Estimate the probability of getting 5 or more heads from 7 spins
>>> # of a biased coin that settles on heads 60% of the time.
>>> def trial[]:
...     return choices['HT', cum_weights=[0.60, 1.00], k=7].count['H'] >= 5
...
>>> sum[trial[] for i in range[10_000]] / 10_000
0.4169

>>> # Probability of the median of 5 samples being in middle two quartiles
>>> def trial[]:
...     return 2_500 > sum[trial[] for i in range[10_000]] / 10_000
0.7958
7 được nâng lên nếu tất cả các trọng số bằng không.

Đối với một hạt giống nhất định, hàm

# Example from "Statistics is Easy" by Dennis Shasha and Manda Wilson
from statistics import fmean as mean
from random import shuffle

drug = [54, 73, 53, 70, 73, 68, 52, 65, 65]
placebo = [54, 51, 58, 44, 55, 52, 42, 47, 58, 46]
observed_diff = mean[drug] - mean[placebo]

n = 10_000
count = 0
combined = drug + placebo
for i in range[n]:
    shuffle[combined]
    new_diff = mean[combined[:len[drug]]] - mean[combined[len[drug]:]]
    count += [new_diff >= observed_diff]

print[f'{n} label reshufflings produced only {count} instances with a difference']
print[f'at least as extreme as the observed difference of {observed_diff:.1f}.']
print[f'The one-sided p-value of {count / n:.4f} leads us to reject the null']
print[f'hypothesis that there is no difference between the drug and the placebo.']
2 có trọng số bằng nhau thường tạo ra một chuỗi khác với các cuộc gọi lặp lại đến
# Example from "Statistics is Easy" by Dennis Shasha and Manda Wilson
from statistics import fmean as mean
from random import shuffle

drug = [54, 73, 53, 70, 73, 68, 52, 65, 65]
placebo = [54, 51, 58, 44, 55, 52, 42, 47, 58, 46]
observed_diff = mean[drug] - mean[placebo]

n = 10_000
count = 0
combined = drug + placebo
for i in range[n]:
    shuffle[combined]
    new_diff = mean[combined[:len[drug]]] - mean[combined[len[drug]:]]
    count += [new_diff >= observed_diff]

print[f'{n} label reshufflings produced only {count} instances with a difference']
print[f'at least as extreme as the observed difference of {observed_diff:.1f}.']
print[f'The one-sided p-value of {count / n:.4f} leads us to reject the null']
print[f'hypothesis that there is no difference between the drug and the placebo.']
3. Thuật toán được sử dụng bởi
# Example from "Statistics is Easy" by Dennis Shasha and Manda Wilson
from statistics import fmean as mean
from random import shuffle

drug = [54, 73, 53, 70, 73, 68, 52, 65, 65]
placebo = [54, 51, 58, 44, 55, 52, 42, 47, 58, 46]
observed_diff = mean[drug] - mean[placebo]

n = 10_000
count = 0
combined = drug + placebo
for i in range[n]:
    shuffle[combined]
    new_diff = mean[combined[:len[drug]]] - mean[combined[len[drug]:]]
    count += [new_diff >= observed_diff]

print[f'{n} label reshufflings produced only {count} instances with a difference']
print[f'at least as extreme as the observed difference of {observed_diff:.1f}.']
print[f'The one-sided p-value of {count / n:.4f} leads us to reject the null']
print[f'hypothesis that there is no difference between the drug and the placebo.']
2 sử dụng số học điểm nổi cho tính nhất quán và tốc độ bên trong. Thuật toán được sử dụng bởi
# Example from "Statistics is Easy" by Dennis Shasha and Manda Wilson
from statistics import fmean as mean
from random import shuffle

drug = [54, 73, 53, 70, 73, 68, 52, 65, 65]
placebo = [54, 51, 58, 44, 55, 52, 42, 47, 58, 46]
observed_diff = mean[drug] - mean[placebo]

n = 10_000
count = 0
combined = drug + placebo
for i in range[n]:
    shuffle[combined]
    new_diff = mean[combined[:len[drug]]] - mean[combined[len[drug]:]]
    count += [new_diff >= observed_diff]

print[f'{n} label reshufflings produced only {count} instances with a difference']
print[f'at least as extreme as the observed difference of {observed_diff:.1f}.']
print[f'The one-sided p-value of {count / n:.4f} leads us to reject the null']
print[f'hypothesis that there is no difference between the drug and the placebo.']
3 mặc định cho số học số nguyên với các lựa chọn lặp đi lặp lại để tránh các độ lệch nhỏ khỏi lỗi làm tròn.

Mới trong phiên bản 3.6.

Đã thay đổi trong phiên bản 3.9: tăng

>>> # Six roulette wheel spins [weighted sampling with replacement]
>>> choices[['red', 'black', 'green'], [18, 18, 2], k=6]
['red', 'green', 'black', 'black', 'red', 'black']

>>> # Deal 20 cards without replacement from a deck
>>> # of 52 playing cards, and determine the proportion of cards
>>> # with a ten-value:  ten, jack, queen, or king.
>>> dealt = sample[['tens', 'low cards'], counts=[16, 36], k=20]
>>> dealt.count['tens'] / 20
0.15

>>> # Estimate the probability of getting 5 or more heads from 7 spins
>>> # of a biased coin that settles on heads 60% of the time.
>>> def trial[]:
...     return choices['HT', cum_weights=[0.60, 1.00], k=7].count['H'] >= 5
...
>>> sum[trial[] for i in range[10_000]] / 10_000
0.4169

>>> # Probability of the median of 5 samples being in middle two quartiles
>>> def trial[]:
...     return 2_500 > sum[trial[] for i in range[10_000]] / 10_000
0.7958
7 nếu tất cả các trọng số bằng không.Raises a
>>> # Six roulette wheel spins [weighted sampling with replacement]
>>> choices[['red', 'black', 'green'], [18, 18, 2], k=6]
['red', 'green', 'black', 'black', 'red', 'black']

>>> # Deal 20 cards without replacement from a deck
>>> # of 52 playing cards, and determine the proportion of cards
>>> # with a ten-value:  ten, jack, queen, or king.
>>> dealt = sample[['tens', 'low cards'], counts=[16, 36], k=20]
>>> dealt.count['tens'] / 20
0.15

>>> # Estimate the probability of getting 5 or more heads from 7 spins
>>> # of a biased coin that settles on heads 60% of the time.
>>> def trial[]:
...     return choices['HT', cum_weights=[0.60, 1.00], k=7].count['H'] >= 5
...
>>> sum[trial[] for i in range[10_000]] / 10_000
0.4169

>>> # Probability of the median of 5 samples being in middle two quartiles
>>> def trial[]:
...     return 2_500 > sum[trial[] for i in range[10_000]] / 10_000
0.7958
7 if all weights are zero.

ngẫu nhiên.shuffle [x] ¶shuffle[x]

Xáo trộn chuỗi x tại chỗ.

Để xáo trộn một chuỗi bất biến và trả lại một danh sách xáo trộn mới, hãy sử dụng

# Example from "Statistics is Easy" by Dennis Shasha and Manda Wilson
from statistics import fmean as mean
from random import shuffle

drug = [54, 73, 53, 70, 73, 68, 52, 65, 65]
placebo = [54, 51, 58, 44, 55, 52, 42, 47, 58, 46]
observed_diff = mean[drug] - mean[placebo]

n = 10_000
count = 0
combined = drug + placebo
for i in range[n]:
    shuffle[combined]
    new_diff = mean[combined[:len[drug]]] - mean[combined[len[drug]:]]
    count += [new_diff >= observed_diff]

print[f'{n} label reshufflings produced only {count} instances with a difference']
print[f'at least as extreme as the observed difference of {observed_diff:.1f}.']
print[f'The one-sided p-value of {count / n:.4f} leads us to reject the null']
print[f'hypothesis that there is no difference between the drug and the placebo.']
7 thay thế.

Lưu ý rằng ngay cả đối với

# Example from "Statistics is Easy" by Dennis Shasha and Manda Wilson
from statistics import fmean as mean
from random import shuffle

drug = [54, 73, 53, 70, 73, 68, 52, 65, 65]
placebo = [54, 51, 58, 44, 55, 52, 42, 47, 58, 46]
observed_diff = mean[drug] - mean[placebo]

n = 10_000
count = 0
combined = drug + placebo
for i in range[n]:
    shuffle[combined]
    new_diff = mean[combined[:len[drug]]] - mean[combined[len[drug]:]]
    count += [new_diff >= observed_diff]

print[f'{n} label reshufflings produced only {count} instances with a difference']
print[f'at least as extreme as the observed difference of {observed_diff:.1f}.']
print[f'The one-sided p-value of {count / n:.4f} leads us to reject the null']
print[f'hypothesis that there is no difference between the drug and the placebo.']
8 nhỏ, tổng số hoán vị của X có thể nhanh chóng phát triển lớn hơn thời gian của hầu hết các máy phát số ngẫu nhiên. Điều này ngụ ý rằng hầu hết các hoán vị của một chuỗi dài không bao giờ có thể được tạo ra. Ví dụ, một chuỗi độ dài 2080 là lớn nhất có thể phù hợp trong khoảng thời gian của bộ tạo số ngẫu nhiên Mersenne Twister.

Không dùng nữa kể từ phiên bản 3.9, bị xóa trong phiên bản 3.11: Tham số tùy chọn ngẫu nhiên.The optional parameter random.

ngẫu nhiên.sample [dân số, k, *, số lượng = không] ¶sample[population, k, *, counts=None]

Trả về một danh sách chiều dài k của các yếu tố duy nhất được chọn từ chuỗi dân số. Được sử dụng để lấy mẫu ngẫu nhiên mà không cần thay thế.

Trả về một danh sách mới chứa các yếu tố từ dân số trong khi để lại dân số ban đầu không thay đổi. Danh sách kết quả theo thứ tự lựa chọn để tất cả các lớp phụ cũng sẽ là các mẫu ngẫu nhiên hợp lệ. Điều này cho phép người chiến thắng xổ số [mẫu] được phân chia thành giải thưởng lớn và người chiến thắng vị trí thứ hai [các phụ].

Các thành viên của dân số không cần phải có thể băm hoặc duy nhất. Nếu dân số chứa lặp lại, thì mỗi lần xuất hiện là một lựa chọn có thể trong mẫu.hashable or unique. If the population contains repeats, then each occurrence is a possible selection in the sample.

Các phần tử lặp lại có thể được chỉ định một lần hoặc với tham số số lượng từ khóa chỉ tùy chọn. Ví dụ,

# Example from "Statistics is Easy" by Dennis Shasha and Manda Wilson
from statistics import fmean as mean
from random import shuffle

drug = [54, 73, 53, 70, 73, 68, 52, 65, 65]
placebo = [54, 51, 58, 44, 55, 52, 42, 47, 58, 46]
observed_diff = mean[drug] - mean[placebo]

n = 10_000
count = 0
combined = drug + placebo
for i in range[n]:
    shuffle[combined]
    new_diff = mean[combined[:len[drug]]] - mean[combined[len[drug]:]]
    count += [new_diff >= observed_diff]

print[f'{n} label reshufflings produced only {count} instances with a difference']
print[f'at least as extreme as the observed difference of {observed_diff:.1f}.']
print[f'The one-sided p-value of {count / n:.4f} leads us to reject the null']
print[f'hypothesis that there is no difference between the drug and the placebo.']
9 tương đương với
from heapq import heapify, heapreplace
from random import expovariate, gauss
from statistics import mean, quantiles

average_arrival_interval = 5.6
average_service_time = 15.0
stdev_service_time = 3.5
num_servers = 3

waits = []
arrival_time = 0.0
servers = [0.0] * num_servers  # time when each server becomes available
heapify[servers]
for i in range[1_000_000]:
    arrival_time += expovariate[1.0 / average_arrival_interval]
    next_server_available = servers[0]
    wait = max[0.0, next_server_available - arrival_time]
    waits.append[wait]
    service_duration = max[0.0, gauss[average_service_time, stdev_service_time]]
    service_completed = arrival_time + wait + service_duration
    heapreplace[servers, service_completed]

print[f'Mean wait: {mean[waits]:.1f}   Max wait: {max[waits]:.1f}']
print['Quartiles:', [round[q, 1] for q in quantiles[waits]]]
0.

Để chọn một mẫu từ một loạt các số nguyên, hãy sử dụng đối tượng

>>> random[]                             # Random float:  0.0 >> uniform[2.5, 10.0]                   # Random float:  2.5 > expovariate[1 / 5]                   # Interval between arrivals averaging 5 seconds
5.148957571865031

>>> randrange[10]                        # Integer from 0 to 9 inclusive
7

>>> randrange[0, 101, 2]                 # Even integer from 0 to 100 inclusive
26

>>> choice[['win', 'lose', 'draw']]      # Single random element from a sequence
'draw'

>>> deck = 'ace two three four'.split[]
>>> shuffle[deck]                        # Shuffle a list
>>> deck
['four', 'two', 'ace', 'three']

>>> sample[[10, 20, 30, 40, 50], k=4]    # Four samples without replacement
[40, 10, 50, 30]
9 làm đối số. Điều này đặc biệt nhanh chóng và hiệu quả không gian để lấy mẫu từ một dân số lớn:
from heapq import heapify, heapreplace
from random import expovariate, gauss
from statistics import mean, quantiles

average_arrival_interval = 5.6
average_service_time = 15.0
stdev_service_time = 3.5
num_servers = 3

waits = []
arrival_time = 0.0
servers = [0.0] * num_servers  # time when each server becomes available
heapify[servers]
for i in range[1_000_000]:
    arrival_time += expovariate[1.0 / average_arrival_interval]
    next_server_available = servers[0]
    wait = max[0.0, next_server_available - arrival_time]
    waits.append[wait]
    service_duration = max[0.0, gauss[average_service_time, stdev_service_time]]
    service_completed = arrival_time + wait + service_duration
    heapreplace[servers, service_completed]

print[f'Mean wait: {mean[waits]:.1f}   Max wait: {max[waits]:.1f}']
print['Quartiles:', [round[q, 1] for q in quantiles[waits]]]
2.

Nếu kích thước mẫu lớn hơn kích thước dân số, thì

>>> # Six roulette wheel spins [weighted sampling with replacement]
>>> choices[['red', 'black', 'green'], [18, 18, 2], k=6]
['red', 'green', 'black', 'black', 'red', 'black']

>>> # Deal 20 cards without replacement from a deck
>>> # of 52 playing cards, and determine the proportion of cards
>>> # with a ten-value:  ten, jack, queen, or king.
>>> dealt = sample[['tens', 'low cards'], counts=[16, 36], k=20]
>>> dealt.count['tens'] / 20
0.15

>>> # Estimate the probability of getting 5 or more heads from 7 spins
>>> # of a biased coin that settles on heads 60% of the time.
>>> def trial[]:
...     return choices['HT', cum_weights=[0.60, 1.00], k=7].count['H'] >= 5
...
>>> sum[trial[] for i in range[10_000]] / 10_000
0.4169

>>> # Probability of the median of 5 samples being in middle two quartiles
>>> def trial[]:
...     return 2_500 > sum[trial[] for i in range[10_000]] / 10_000
0.7958
7 sẽ được nâng lên.

Đã thay đổi trong phiên bản 3.9: Đã thêm tham số Counts.Added the counts parameter.

Thay đổi trong phiên bản 3.11: Dân số phải là một chuỗi. Tự động chuyển đổi các bộ thành danh sách không còn được hỗ trợ.The population must be a sequence. Automatic conversion of sets to lists is no longer supported.

Phân phối có giá trị thực

Các chức năng sau đây tạo ra các phân phối có giá trị thực cụ thể. Các tham số chức năng được đặt tên theo các biến tương ứng trong phương trình phân phối, như được sử dụng trong thực tiễn toán học thông thường; Hầu hết các phương trình này có thể được tìm thấy trong bất kỳ văn bản thống kê.

ngẫu nhiên.random [] ¶random[]

Trả về số điểm nổi ngẫu nhiên tiếp theo trong phạm vi [0,0, 1.0].

ngẫu nhiên.uniform [a, b] ¶uniform[a, b]

Trả về số điểm nổi ngẫu nhiên n sao cho

>>> # Six roulette wheel spins [weighted sampling with replacement]
>>> choices[['red', 'black', 'green'], [18, 18, 2], k=6]
['red', 'green', 'black', 'black', 'red', 'black']

>>> # Deal 20 cards without replacement from a deck
>>> # of 52 playing cards, and determine the proportion of cards
>>> # with a ten-value:  ten, jack, queen, or king.
>>> dealt = sample[['tens', 'low cards'], counts=[16, 36], k=20]
>>> dealt.count['tens'] / 20
0.15

>>> # Estimate the probability of getting 5 or more heads from 7 spins
>>> # of a biased coin that settles on heads 60% of the time.
>>> def trial[]:
...     return choices['HT', cum_weights=[0.60, 1.00], k=7].count['H'] >= 5
...
>>> sum[trial[] for i in range[10_000]] / 10_000
0.4169

>>> # Probability of the median of 5 samples being in middle two quartiles
>>> def trial[]:
...     return 2_500 > sum[trial[] for i in range[10_000]] / 10_000
0.7958
9 cho
from heapq import heapify, heapreplace
from random import expovariate, gauss
from statistics import mean, quantiles

average_arrival_interval = 5.6
average_service_time = 15.0
stdev_service_time = 3.5
num_servers = 3

waits = []
arrival_time = 0.0
servers = [0.0] * num_servers  # time when each server becomes available
heapify[servers]
for i in range[1_000_000]:
    arrival_time += expovariate[1.0 / average_arrival_interval]
    next_server_available = servers[0]
    wait = max[0.0, next_server_available - arrival_time]
    waits.append[wait]
    service_duration = max[0.0, gauss[average_service_time, stdev_service_time]]
    service_completed = arrival_time + wait + service_duration
    heapreplace[servers, service_completed]

print[f'Mean wait: {mean[waits]:.1f}   Max wait: {max[waits]:.1f}']
print['Quartiles:', [round[q, 1] for q in quantiles[waits]]]
5 và
from heapq import heapify, heapreplace
from random import expovariate, gauss
from statistics import mean, quantiles

average_arrival_interval = 5.6
average_service_time = 15.0
stdev_service_time = 3.5
num_servers = 3

waits = []
arrival_time = 0.0
servers = [0.0] * num_servers  # time when each server becomes available
heapify[servers]
for i in range[1_000_000]:
    arrival_time += expovariate[1.0 / average_arrival_interval]
    next_server_available = servers[0]
    wait = max[0.0, next_server_available - arrival_time]
    waits.append[wait]
    service_duration = max[0.0, gauss[average_service_time, stdev_service_time]]
    service_completed = arrival_time + wait + service_duration
    heapreplace[servers, service_completed]

print[f'Mean wait: {mean[waits]:.1f}   Max wait: {max[waits]:.1f}']
print['Quartiles:', [round[q, 1] for q in quantiles[waits]]]
6 cho
from heapq import heapify, heapreplace
from random import expovariate, gauss
from statistics import mean, quantiles

average_arrival_interval = 5.6
average_service_time = 15.0
stdev_service_time = 3.5
num_servers = 3

waits = []
arrival_time = 0.0
servers = [0.0] * num_servers  # time when each server becomes available
heapify[servers]
for i in range[1_000_000]:
    arrival_time += expovariate[1.0 / average_arrival_interval]
    next_server_available = servers[0]
    wait = max[0.0, next_server_available - arrival_time]
    waits.append[wait]
    service_duration = max[0.0, gauss[average_service_time, stdev_service_time]]
    service_completed = arrival_time + wait + service_duration
    heapreplace[servers, service_completed]

print[f'Mean wait: {mean[waits]:.1f}   Max wait: {max[waits]:.1f}']
print['Quartiles:', [round[q, 1] for q in quantiles[waits]]]
7.

Giá trị điểm cuối

from heapq import heapify, heapreplace
from random import expovariate, gauss
from statistics import mean, quantiles

average_arrival_interval = 5.6
average_service_time = 15.0
stdev_service_time = 3.5
num_servers = 3

waits = []
arrival_time = 0.0
servers = [0.0] * num_servers  # time when each server becomes available
heapify[servers]
for i in range[1_000_000]:
    arrival_time += expovariate[1.0 / average_arrival_interval]
    next_server_available = servers[0]
    wait = max[0.0, next_server_available - arrival_time]
    waits.append[wait]
    service_duration = max[0.0, gauss[average_service_time, stdev_service_time]]
    service_completed = arrival_time + wait + service_duration
    heapreplace[servers, service_completed]

print[f'Mean wait: {mean[waits]:.1f}   Max wait: {max[waits]:.1f}']
print['Quartiles:', [round[q, 1] for q in quantiles[waits]]]
8 có thể hoặc không được đưa vào phạm vi tùy thuộc vào việc làm tròn điểm nổi trong phương trình
from heapq import heapify, heapreplace
from random import expovariate, gauss
from statistics import mean, quantiles

average_arrival_interval = 5.6
average_service_time = 15.0
stdev_service_time = 3.5
num_servers = 3

waits = []
arrival_time = 0.0
servers = [0.0] * num_servers  # time when each server becomes available
heapify[servers]
for i in range[1_000_000]:
    arrival_time += expovariate[1.0 / average_arrival_interval]
    next_server_available = servers[0]
    wait = max[0.0, next_server_available - arrival_time]
    waits.append[wait]
    service_duration = max[0.0, gauss[average_service_time, stdev_service_time]]
    service_completed = arrival_time + wait + service_duration
    heapreplace[servers, service_completed]

print[f'Mean wait: {mean[waits]:.1f}   Max wait: {max[waits]:.1f}']
print['Quartiles:', [round[q, 1] for q in quantiles[waits]]]
9.

ngẫu nhiên.triangular [thấp, cao, chế độ] ¶triangular[low, high, mode]

Trả về một số điểm nổi ngẫu nhiên n sao cho

def random_product[*args, repeat=1]:
    "Random selection from itertools.product[*args, **kwds]"
    pools = [tuple[pool] for pool in args] * repeat
    return tuple[map[random.choice, pools]]

def random_permutation[iterable, r=None]:
    "Random selection from itertools.permutations[iterable, r]"
    pool = tuple[iterable]
    r = len[pool] if r is None else r
    return tuple[random.sample[pool, r]]

def random_combination[iterable, r]:
    "Random selection from itertools.combinations[iterable, r]"
    pool = tuple[iterable]
    n = len[pool]
    indices = sorted[random.sample[range[n], r]]
    return tuple[pool[i] for i in indices]

def random_combination_with_replacement[iterable, r]:
    "Random selection from itertools.combinations_with_replacement[iterable, r]"
    pool = tuple[iterable]
    n = len[pool]
    indices = sorted[random.choices[range[n], k=r]]
    return tuple[pool[i] for i in indices]
0 và với chế độ được chỉ định giữa các giới hạn đó. Giới hạn thấp và cao mặc định là 0 và một. Đối số chế độ mặc định đến điểm giữa giữa các giới hạn, đưa ra phân phối đối xứng.

ngẫu nhiên.betavariate [alpha, beta] ¶betavariate[alpha, beta]

Phân phối beta. Điều kiện trên các tham số là

def random_product[*args, repeat=1]:
    "Random selection from itertools.product[*args, **kwds]"
    pools = [tuple[pool] for pool in args] * repeat
    return tuple[map[random.choice, pools]]

def random_permutation[iterable, r=None]:
    "Random selection from itertools.permutations[iterable, r]"
    pool = tuple[iterable]
    r = len[pool] if r is None else r
    return tuple[random.sample[pool, r]]

def random_combination[iterable, r]:
    "Random selection from itertools.combinations[iterable, r]"
    pool = tuple[iterable]
    n = len[pool]
    indices = sorted[random.sample[range[n], r]]
    return tuple[pool[i] for i in indices]

def random_combination_with_replacement[iterable, r]:
    "Random selection from itertools.combinations_with_replacement[iterable, r]"
    pool = tuple[iterable]
    n = len[pool]
    indices = sorted[random.choices[range[n], k=r]]
    return tuple[pool[i] for i in indices]
1 và
def random_product[*args, repeat=1]:
    "Random selection from itertools.product[*args, **kwds]"
    pools = [tuple[pool] for pool in args] * repeat
    return tuple[map[random.choice, pools]]

def random_permutation[iterable, r=None]:
    "Random selection from itertools.permutations[iterable, r]"
    pool = tuple[iterable]
    r = len[pool] if r is None else r
    return tuple[random.sample[pool, r]]

def random_combination[iterable, r]:
    "Random selection from itertools.combinations[iterable, r]"
    pool = tuple[iterable]
    n = len[pool]
    indices = sorted[random.sample[range[n], r]]
    return tuple[pool[i] for i in indices]

def random_combination_with_replacement[iterable, r]:
    "Random selection from itertools.combinations_with_replacement[iterable, r]"
    pool = tuple[iterable]
    n = len[pool]
    indices = sorted[random.choices[range[n], k=r]]
    return tuple[pool[i] for i in indices]
2. Giá trị trả về nằm trong khoảng từ 0 đến 1.

ngẫu nhiên.expovariate [Lambd] ¶expovariate[lambd]

Phân phối theo cấp số nhân. Lambd là 1,0 chia cho giá trị trung bình mong muốn. Nó nên là khác nhau. .

ngẫu nhiên.gammavariate [alpha, beta] ¶gammavariate[alpha, beta]

Phân phối Gamma. [Không phải hàm gamma!] Điều kiện trên các tham số là

def random_product[*args, repeat=1]:
    "Random selection from itertools.product[*args, **kwds]"
    pools = [tuple[pool] for pool in args] * repeat
    return tuple[map[random.choice, pools]]

def random_permutation[iterable, r=None]:
    "Random selection from itertools.permutations[iterable, r]"
    pool = tuple[iterable]
    r = len[pool] if r is None else r
    return tuple[random.sample[pool, r]]

def random_combination[iterable, r]:
    "Random selection from itertools.combinations[iterable, r]"
    pool = tuple[iterable]
    n = len[pool]
    indices = sorted[random.sample[range[n], r]]
    return tuple[pool[i] for i in indices]

def random_combination_with_replacement[iterable, r]:
    "Random selection from itertools.combinations_with_replacement[iterable, r]"
    pool = tuple[iterable]
    n = len[pool]
    indices = sorted[random.choices[range[n], k=r]]
    return tuple[pool[i] for i in indices]
1 và
def random_product[*args, repeat=1]:
    "Random selection from itertools.product[*args, **kwds]"
    pools = [tuple[pool] for pool in args] * repeat
    return tuple[map[random.choice, pools]]

def random_permutation[iterable, r=None]:
    "Random selection from itertools.permutations[iterable, r]"
    pool = tuple[iterable]
    r = len[pool] if r is None else r
    return tuple[random.sample[pool, r]]

def random_combination[iterable, r]:
    "Random selection from itertools.combinations[iterable, r]"
    pool = tuple[iterable]
    n = len[pool]
    indices = sorted[random.sample[range[n], r]]
    return tuple[pool[i] for i in indices]

def random_combination_with_replacement[iterable, r]:
    "Random selection from itertools.combinations_with_replacement[iterable, r]"
    pool = tuple[iterable]
    n = len[pool]
    indices = sorted[random.choices[range[n], k=r]]
    return tuple[pool[i] for i in indices]
2.

Hàm phân phối xác suất là:

          x ** [alpha - 1] * math.exp[-x / beta]
pdf[x] =  --------------------------------------
            math.gamma[alpha] * beta ** alpha

ngẫu nhiên.gauss [mu = 0,0, sigma = 1.0] ¶gauss[mu=0.0, sigma=1.0]

Phân phối bình thường, còn được gọi là phân phối Gaussian. MU là trung bình, và Sigma là độ lệch chuẩn. Điều này nhanh hơn một chút so với hàm

def random_product[*args, repeat=1]:
    "Random selection from itertools.product[*args, **kwds]"
    pools = [tuple[pool] for pool in args] * repeat
    return tuple[map[random.choice, pools]]

def random_permutation[iterable, r=None]:
    "Random selection from itertools.permutations[iterable, r]"
    pool = tuple[iterable]
    r = len[pool] if r is None else r
    return tuple[random.sample[pool, r]]

def random_combination[iterable, r]:
    "Random selection from itertools.combinations[iterable, r]"
    pool = tuple[iterable]
    n = len[pool]
    indices = sorted[random.sample[range[n], r]]
    return tuple[pool[i] for i in indices]

def random_combination_with_replacement[iterable, r]:
    "Random selection from itertools.combinations_with_replacement[iterable, r]"
    pool = tuple[iterable]
    n = len[pool]
    indices = sorted[random.choices[range[n], k=r]]
    return tuple[pool[i] for i in indices]
5 được xác định dưới đây.

Lưu ý đa luồng: Khi hai luồng gọi chức năng này đồng thời, có thể họ sẽ nhận được cùng một giá trị trả về. Điều này có thể tránh được theo ba cách. 1] Có mỗi luồng sử dụng một thể hiện khác nhau của trình tạo số ngẫu nhiên. 2] Đặt khóa xung quanh tất cả các cuộc gọi. 3] Thay vào đó, sử dụng chức năng chậm hơn, nhưng an toàn

def random_product[*args, repeat=1]:
    "Random selection from itertools.product[*args, **kwds]"
    pools = [tuple[pool] for pool in args] * repeat
    return tuple[map[random.choice, pools]]

def random_permutation[iterable, r=None]:
    "Random selection from itertools.permutations[iterable, r]"
    pool = tuple[iterable]
    r = len[pool] if r is None else r
    return tuple[random.sample[pool, r]]

def random_combination[iterable, r]:
    "Random selection from itertools.combinations[iterable, r]"
    pool = tuple[iterable]
    n = len[pool]
    indices = sorted[random.sample[range[n], r]]
    return tuple[pool[i] for i in indices]

def random_combination_with_replacement[iterable, r]:
    "Random selection from itertools.combinations_with_replacement[iterable, r]"
    pool = tuple[iterable]
    n = len[pool]
    indices = sorted[random.choices[range[n], k=r]]
    return tuple[pool[i] for i in indices]
5.

Đã thay đổi trong phiên bản 3.11: MU và Sigma hiện có các đối số mặc định.mu and sigma now have default arguments.

Random.LognorMvariate [MU, Sigma] ¶lognormvariate[mu, sigma]

Phân phối lognormal. Nếu bạn lấy logarit tự nhiên của phân phối này, bạn sẽ nhận được một phân phối bình thường với MU trung bình và độ lệch chuẩn. MU có thể có bất kỳ giá trị nào, và Sigma phải lớn hơn 0.

ngẫu nhiênnormalvariate[mu=0.0, sigma=1.0]

Phân phối bình thường. MU là trung bình, và Sigma là độ lệch chuẩn.

Đã thay đổi trong phiên bản 3.11: MU và Sigma hiện có các đối số mặc định.mu and sigma now have default arguments.

Random.LognorMvariate [MU, Sigma] ¶vonmisesvariate[mu, kappa]

Phân phối lognormal. Nếu bạn lấy logarit tự nhiên của phân phối này, bạn sẽ nhận được một phân phối bình thường với MU trung bình và độ lệch chuẩn. MU có thể có bất kỳ giá trị nào, và Sigma phải lớn hơn 0.

ngẫu nhiênparetovariate[alpha]

Phân phối bình thường. MU là trung bình, và Sigma là độ lệch chuẩn.

ngẫu nhiên.vonmisevariate [MU, Kappa] ¶weibullvariate[alpha, beta]

MU là góc trung bình, được biểu thị bằng radian trong khoảng từ 0 đến 2*pi và kappa là tham số nồng độ, phải lớn hơn hoặc bằng không. Nếu kappa bằng 0, phân phối này sẽ giảm xuống góc ngẫu nhiên đồng đều trong phạm vi 0 đến 2*pi.

ngẫu nhiên.paretovariate [alpha] ¶

Phân phối Pareto. Alpha là tham số hình dạng. random.Random[[seed]]

ngẫu nhiên.weibullvariate [alpha, beta] ¶

Phân phối Weibull. Alpha là tham số tỷ lệ và beta là tham số hình dạng.In the future, the seed must be one of the following types:

def random_product[*args, repeat=1]:
    "Random selection from itertools.product[*args, **kwds]"
    pools = [tuple[pool] for pool in args] * repeat
    return tuple[map[random.choice, pools]]

def random_permutation[iterable, r=None]:
    "Random selection from itertools.permutations[iterable, r]"
    pool = tuple[iterable]
    r = len[pool] if r is None else r
    return tuple[random.sample[pool, r]]

def random_combination[iterable, r]:
    "Random selection from itertools.combinations[iterable, r]"
    pool = tuple[iterable]
    n = len[pool]
    indices = sorted[random.sample[range[n], r]]
    return tuple[pool[i] for i in indices]

def random_combination_with_replacement[iterable, r]:
    "Random selection from itertools.combinations_with_replacement[iterable, r]"
    pool = tuple[iterable]
    n = len[pool]
    indices = sorted[random.choices[range[n], k=r]]
    return tuple[pool[i] for i in indices]
8,
          x ** [alpha - 1] * math.exp[-x / beta]
pdf[x] =  --------------------------------------
            math.gamma[alpha] * beta ** alpha
4,
          x ** [alpha - 1] * math.exp[-x / beta]
pdf[x] =  --------------------------------------
            math.gamma[alpha] * beta ** alpha
8,
          x ** [alpha - 1] * math.exp[-x / beta]
pdf[x] =  --------------------------------------
            math.gamma[alpha] * beta ** alpha
1,
          x ** [alpha - 1] * math.exp[-x / beta]
pdf[x] =  --------------------------------------
            math.gamma[alpha] * beta ** alpha
2, or
          x ** [alpha - 1] * math.exp[-x / beta]
pdf[x] =  --------------------------------------
            math.gamma[alpha] * beta ** alpha
3.

Máy phát điện thay thế random.SystemRandom[[seed]]

classRandom.random [[hạt giống]] ¶

Lớp thực hiện trình tạo số giả ngẫu nhiên mặc định được sử dụng bởi mô-đun
random.randint[a,b]
5.

Đã không dùng nữa kể từ phiên bản 3.9: Trong tương lai, hạt giống phải là một trong các loại sau:

def random_product[*args, repeat=1]:
    "Random selection from itertools.product[*args, **kwds]"
    pools = [tuple[pool] for pool in args] * repeat
    return tuple[map[random.choice, pools]]

def random_permutation[iterable, r=None]:
    "Random selection from itertools.permutations[iterable, r]"
    pool = tuple[iterable]
    r = len[pool] if r is None else r
    return tuple[random.sample[pool, r]]

def random_combination[iterable, r]:
    "Random selection from itertools.combinations[iterable, r]"
    pool = tuple[iterable]
    n = len[pool]
    indices = sorted[random.sample[range[n], r]]
    return tuple[pool[i] for i in indices]

def random_combination_with_replacement[iterable, r]:
    "Random selection from itertools.combinations_with_replacement[iterable, r]"
    pool = tuple[iterable]
    n = len[pool]
    indices = sorted[random.choices[range[n], k=r]]
    return tuple[pool[i] for i in indices]
8,
          x ** [alpha - 1] * math.exp[-x / beta]
pdf[x] =  --------------------------------------
            math.gamma[alpha] * beta ** alpha
4,
          x ** [alpha - 1] * math.exp[-x / beta]
pdf[x] =  --------------------------------------
            math.gamma[alpha] * beta ** alpha
8,
          x ** [alpha - 1] * math.exp[-x / beta]
pdf[x] =  --------------------------------------
            math.gamma[alpha] * beta ** alpha
1,
          x ** [alpha - 1] * math.exp[-x / beta]
pdf[x] =  --------------------------------------
            math.gamma[alpha] * beta ** alpha
2 hoặc
          x ** [alpha - 1] * math.exp[-x / beta]
pdf[x] =  --------------------------------------
            math.gamma[alpha] * beta ** alpha
3.

classRandom.SystemRandom [[hạt giống]] ¶

  • Lớp sử dụng hàm

    random.randint[a,b]
    
    7 để tạo số ngẫu nhiên từ các nguồn được cung cấp bởi hệ điều hành. Không có sẵn trên tất cả các hệ thống. Không dựa vào trạng thái phần mềm và các chuỗi không thể tái sản xuất. Theo đó, phương pháp
    random.randint[a,b]
    
    0 không có hiệu lực và bị bỏ qua. Các phương pháp
    random.randint[a,b]
    
    1 và
    random.randint[a,b]
    
    2 tăng
    5
    
    08 nếu được gọi.

  • Ghi chú về khả năng tái sản xuất

Đôi khi rất hữu ích để có thể tái tạo các chuỗi được đưa ra bởi một trình tạo số giả giả. Bằng cách sử dụng lại giá trị hạt giống, chuỗi tương tự phải được tái tạo từ chạy để chạy miễn là nhiều luồng không chạy.

Hầu hết các thuật toán và chức năng gieo hạt ngẫu nhiên đều có thể thay đổi trên các phiên bản Python, nhưng hai khía cạnh được đảm bảo không thay đổi:

>>> random[]                             # Random float:  0.0 >> uniform[2.5, 10.0]                   # Random float:  2.5 > expovariate[1 / 5]                   # Interval between arrivals averaging 5 seconds
5.148957571865031

>>> randrange[10]                        # Integer from 0 to 9 inclusive
7

>>> randrange[0, 101, 2]                 # Even integer from 0 to 100 inclusive
26

>>> choice[['win', 'lose', 'draw']]      # Single random element from a sequence
'draw'

>>> deck = 'ace two three four'.split[]
>>> shuffle[deck]                        # Shuffle a list
>>> deck
['four', 'two', 'ace', 'three']

>>> sample[[10, 20, 30, 40, 50], k=4]    # Four samples without replacement
[40, 10, 50, 30]

Simulations:

>>> # Six roulette wheel spins [weighted sampling with replacement]
>>> choices[['red', 'black', 'green'], [18, 18, 2], k=6]
['red', 'green', 'black', 'black', 'red', 'black']

>>> # Deal 20 cards without replacement from a deck
>>> # of 52 playing cards, and determine the proportion of cards
>>> # with a ten-value:  ten, jack, queen, or king.
>>> dealt = sample[['tens', 'low cards'], counts=[16, 36], k=20]
>>> dealt.count['tens'] / 20
0.15

>>> # Estimate the probability of getting 5 or more heads from 7 spins
>>> # of a biased coin that settles on heads 60% of the time.
>>> def trial[]:
...     return choices['HT', cum_weights=[0.60, 1.00], k=7].count['H'] >= 5
...
>>> sum[trial[] for i in range[10_000]] / 10_000
0.4169

>>> # Probability of the median of 5 samples being in middle two quartiles
>>> def trial[]:
...     return 2_500 > sum[trial[] for i in range[10_000]] / 10_000
0.7958

Nếu một phương pháp gieo hạt mới được thêm vào, thì một máy gieo hạt tương thích ngược sẽ được cung cấp.

# //www.thoughtco.com/example-of-bootstrapping-3126155
from statistics import fmean as mean
from random import choices

data = [41, 50, 29, 37, 81, 30, 73, 63, 20, 35, 68, 22, 60, 31, 95]
means = sorted[mean[choices[data, k=len[data]]] for i in range[100]]
print[f'The sample mean of {mean[data]:.1f} has a 90% confidence '
      f'interval from {means[5]:.1f} to {means[94]:.1f}']

Phương pháp máy phát điện ____ ____ ____15 sẽ tiếp tục tạo ra cùng một chuỗi khi máy gieo hạt tương thích được cho cùng một hạt giống.

# Example from "Statistics is Easy" by Dennis Shasha and Manda Wilson
from statistics import fmean as mean
from random import shuffle

drug = [54, 73, 53, 70, 73, 68, 52, 65, 65]
placebo = [54, 51, 58, 44, 55, 52, 42, 47, 58, 46]
observed_diff = mean[drug] - mean[placebo]

n = 10_000
count = 0
combined = drug + placebo
for i in range[n]:
    shuffle[combined]
    new_diff = mean[combined[:len[drug]]] - mean[combined[len[drug]:]]
    count += [new_diff >= observed_diff]

print[f'{n} label reshufflings produced only {count} instances with a difference']
print[f'at least as extreme as the observed difference of {observed_diff:.1f}.']
print[f'The one-sided p-value of {count / n:.4f} leads us to reject the null']
print[f'hypothesis that there is no difference between the drug and the placebo.']

Ví dụ;

from heapq import heapify, heapreplace
from random import expovariate, gauss
from statistics import mean, quantiles

average_arrival_interval = 5.6
average_service_time = 15.0
stdev_service_time = 3.5
num_servers = 3

waits = []
arrival_time = 0.0
servers = [0.0] * num_servers  # time when each server becomes available
heapify[servers]
for i in range[1_000_000]:
    arrival_time += expovariate[1.0 / average_arrival_interval]
    next_server_available = servers[0]
    wait = max[0.0, next_server_available - arrival_time]
    waits.append[wait]
    service_duration = max[0.0, gauss[average_service_time, stdev_service_time]]
    service_completed = arrival_time + wait + service_duration
    heapreplace[servers, service_completed]

print[f'Mean wait: {mean[waits]:.1f}   Max wait: {max[waits]:.1f}']
print['Quartiles:', [round[q, 1] for q in quantiles[waits]]]

Ví dụ cơ bản:

Ví dụ về bootstrapping thống kê bằng cách sử dụng thay thế với sự thay thế để ước tính khoảng tin cậy cho giá trị trung bình của một mẫu:

Ví dụ về thử nghiệm hoán vị lấy mẫu để xác định ý nghĩa thống kê hoặc giá trị p của sự khác biệt quan sát được giữa các tác dụng của thuốc so với giả dược:

Mô phỏng thời gian đến và giao hàng dịch vụ cho hàng đợi Multiserver:

Xem thêm

Thống kê cho tin tặc Hướng dẫn video của Jake Vanderplas về phân tích thống kê chỉ bằng một vài khái niệm cơ bản bao gồm mô phỏng, lấy mẫu, xáo trộn và xác thực chéo.

def random_product[*args, repeat=1]:
    "Random selection from itertools.product[*args, **kwds]"
    pools = [tuple[pool] for pool in args] * repeat
    return tuple[map[random.choice, pools]]

def random_permutation[iterable, r=None]:
    "Random selection from itertools.permutations[iterable, r]"
    pool = tuple[iterable]
    r = len[pool] if r is None else r
    return tuple[random.sample[pool, r]]

def random_combination[iterable, r]:
    "Random selection from itertools.combinations[iterable, r]"
    pool = tuple[iterable]
    n = len[pool]
    indices = sorted[random.sample[range[n], r]]
    return tuple[pool[i] for i in indices]

def random_combination_with_replacement[iterable, r]:
    "Random selection from itertools.combinations_with_replacement[iterable, r]"
    pool = tuple[iterable]
    n = len[pool]
    indices = sorted[random.choices[range[n], k=r]]
    return tuple[pool[i] for i in indices]

Mô phỏng kinh tế Một mô phỏng thị trường của Peter Norvig cho thấy việc sử dụng hiệu quả nhiều công cụ và phân phối được cung cấp bởi mô -đun này [Gauss, đồng phục, mẫu, betavariate, lựa chọn, hình tam giác và randrange].

Giới thiệu cụ thể về xác suất [sử dụng Python] Hướng dẫn của Peter Norvig bao gồm những điều cơ bản của lý thuyết xác suất, cách viết mô phỏng và cách thực hiện phân tích dữ liệu bằng Python.

5
0

Công thức nấu ăn¶real valued distributions in the class will use the new method:

5
1

Công thức tương đương về mặt khái niệm với một thuật toán chọn từ tất cả các bội số của 2⁻⁻ trong phạm vi 0,0 x

Bài Viết Liên Quan

Chủ Đề