<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                ### 導航 - [索引](../genindex.xhtml "總目錄") - [模塊](../py-modindex.xhtml "Python 模塊索引") | - [下一頁](statistics.xhtml "statistics --- Mathematical statistics functions") | - [上一頁](fractions.xhtml "fractions --- 分數") | - ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png) - [Python](https://www.python.org/) ? - zh\_CN 3.7.3 [文檔](../index.xhtml) ? - [Python 標準庫](index.xhtml) ? - [數字和數學模塊](numeric.xhtml) ? - $('.inline-search').show(0); | # [`random`](#module-random "random: Generate pseudo-random numbers with various common distributions.") --- 生成偽隨機數 **源碼:** [Lib/random.py](https://github.com/python/cpython/tree/3.7/Lib/random.py) \[https://github.com/python/cpython/tree/3.7/Lib/random.py\] - - - - - - 該模塊實現了各種分布的偽隨機數生成器。 對于整數,從范圍中有統一的選擇。 對于序列,存在隨機元素的統一選擇、用于生成列表的隨機排列的函數、以及用于隨機抽樣而無需替換的函數。 在實數軸上,有計算均勻、正態(高斯)、對數正態、負指數、伽馬和貝塔分布的函數。 為了生成角度分布,可以使用 von Mises 分布。 幾乎所有模塊函數都依賴于基本函數 [`random()`](#random.random "random.random") ,它在半開放區間 \[0.0,1.0) 內均勻生成隨機浮點數。 Python 使用 Mersenne Twister 作為核心生成器。 它產生 53 位精度浮點數,周期為 2\*\*19937-1 ,其在 C 中的底層實現既快又線程安全。 Mersenne Twister 是現存最廣泛測試的隨機數發生器之一。 但是,因為完全確定性,它不適用于所有目的,并且完全不適合加密目的。 這個模塊提供的函數實際上是 [`random.Random`](#random.Random "random.Random") 類的隱藏實例的綁定方法。 你可以實例化自己的 [`Random`](#random.Random "random.Random") 類實例以獲取不共享狀態的生成器。 如果你想使用自己設計的不同基礎生成器,類 [`Random`](#random.Random "random.Random") 也可以作為子類:在這種情況下,重載 `random()` 、 `seed()` 、 `getstate()` 以及 `setstate()` 方法。可選地,新生成器可以提供 `getrandbits()` 方法——這允許 [`randrange()`](#random.randrange "random.randrange") 在任意大的范圍內產生選擇。 [`random`](#module-random "random: Generate pseudo-random numbers with various common distributions.") 模塊還提供 [`SystemRandom`](#random.SystemRandom "random.SystemRandom") 類,它使用系統函數 [`os.urandom()`](os.xhtml#os.urandom "os.urandom") 從操作系統提供的源生成隨機數。 警告 不應將此模塊的偽隨機生成器用于安全目的。 有關安全性或加密用途,請參閱 [`secrets`](secrets.xhtml#module-secrets "secrets: Generate secure random numbers for managing secrets.") 模塊。 參見 M. Matsumoto and T. Nishimura, "Mersenne Twister: A 623-dimensionally equidistributed uniform pseudorandom number generator", ACM Transactions on Modeling and Computer Simulation Vol. 8, No. 1, January pp.3--30 1998. [Complementary-Multiply-with-Carry recipe](https://code.activestate.com/recipes/576707/) \[https://code.activestate.com/recipes/576707/\] 用于兼容的替代隨機數發生器,具有長周期和相對簡單的更新操作。 ## 簿記功能 `random.``seed`(*a=None*, *version=2*)初始化隨機數生成器。 如果 *a* 被省略或為 `None` ,則使用當前系統時間。 如果操作系統提供隨機源,則使用它們而不是系統時間(有關可用性的詳細信息,請參閱 [`os.urandom()`](os.xhtml#os.urandom "os.urandom") 函數)。 如果 *a* 是 int 類型,則直接使用。 對于版本2(默認的),[`str`](stdtypes.xhtml#str "str") 、 [`bytes`](stdtypes.xhtml#bytes "bytes") 或 [`bytearray`](stdtypes.xhtml#bytearray "bytearray") 對象轉換為 [`int`](functions.xhtml#int "int") 并使用它的所有位。 對于版本1(用于從舊版本的Python再現隨機序列),用于 [`str`](stdtypes.xhtml#str "str") 和 [`bytes`](stdtypes.xhtml#bytes "bytes") 的算法生成更窄的種子范圍。 在 3.2 版更改: 已移至版本2方案,該方案使用字符串種子中的所有位。 `random.``getstate`()返回捕獲生成器當前內部狀態的對象。 這個對象可以傳遞給 [`setstate()`](#random.setstate "random.setstate") 來恢復狀態。 `random.``setstate`(*state*)*state* 應該是從之前調用 [`getstate()`](#random.getstate "random.getstate") 獲得的,并且 [`setstate()`](#random.setstate "random.setstate") 將生成器的內部狀態恢復到 [`getstate()`](#random.getstate "random.getstate") 被調用時的狀態。 `random.``getrandbits`(*k*)返回帶有 *k* 位隨機的Python整數。 此方法隨 MersenneTwister 生成器一起提供,其他一些生成器也可以將其作為API的可選部分提供。 如果可用,[`getrandbits()`](#random.getrandbits "random.getrandbits") 啟用 [`randrange()`](#random.randrange "random.randrange") 來處理任意大范圍。 ## 整數用函數 `random.``randrange`(*stop*)`random.``randrange`(*start*, *stop*\[, *step*\])從 `range(start, stop, step)` 返回一個隨機選擇的元素。 這相當于 `choice(range(start, stop, step))` ,但實際上并沒有構建一個 range 對象。 位置參數模式匹配 [`range()`](stdtypes.xhtml#range "range") 。不應使用關鍵字參數,因為該函數可能以意外的方式使用它們。 在 3.2 版更改: [`randrange()`](#random.randrange "random.randrange") 在生成均勻分布的值方面更為復雜。 以前它使用了像``int(random()\*n)``這樣的形式,它可以產生稍微不均勻的分布。 `random.``randint`(*a*, *b*)返回隨機整數 *N* 滿足 `a <= N <= b`。相當于 `randrange(a, b+1)`。 ## 序列用函數 `random.``choice`(*seq*)從非空序列 *seq* 返回一個隨機元素。 如果 *seq* 為空,則引發 [`IndexError`](exceptions.xhtml#IndexError "IndexError")。 `random.``choices`(*population*, *weights=None*, *\**, *cum\_weights=None*, *k=1*)從\*population\*中選擇替換,返回大小為 *k* 的元素列表。 如果 *population* 為空,則引發 [`IndexError`](exceptions.xhtml#IndexError "IndexError")。 如果指定了 *weight* 序列,則根據相對權重進行選擇。 或者,如果給出 *cum\_weights* 序列,則根據累積權重(可能使用 [`itertools.accumulate()`](itertools.xhtml#itertools.accumulate "itertools.accumulate") 計算)進行選擇。 例如,相對權重``\[10, 5, 30, 5\]``相當于累積權重``\[10, 15, 45, 50\]``。 在內部,相對權重在進行選擇之前會轉換為累積權重,因此提供累積權重可以節省工作量。 如果既未指定 *weight* 也未指定 *cum\_weights* ,則以相等的概率進行選擇。 如果提供了權重序列,則它必須與 *population* 序列的長度相同。 一個 [`TypeError`](exceptions.xhtml#TypeError "TypeError") 指定了 *weights* 和\*cum\_weights\*。 *weights* 或 *cum\_weights* 可以使用任何與 [`random()`](#module-random "random: Generate pseudo-random numbers with various common distributions.") 返回的 [`float`](functions.xhtml#float "float") 值互操作的數值類型(包括整數,浮點數和分數但不包括十進制小數)。 對于給定的種子,具有相等加權的 [`choices()`](#random.choices "random.choices") 函數通常產生與重復調用 [`choice()`](#random.choice "random.choice") 不同的序列。 [`choices()`](#random.choices "random.choices") 使用的算法使用浮點運算來實現內部一致性和速度。 [`choice()`](#random.choice "random.choice") 使用的算法默認為重復選擇的整數運算,以避免因舍入誤差引起的小偏差。 3\.6 新版功能. `random.``shuffle`(*x*\[, *random*\])將序列 *x* 隨機打亂位置。 可選參數 *random* 是一個0參數函數,在 \[0.0, 1.0) 中返回隨機浮點數;默認情況下,這是函數 [`random()`](#random.random "random.random") 。 要改變一個不可變的序列并返回一個新的打亂列表,請使用``sample(x, k=len(x))``。 請注意,即使對于小的 `len(x)`,*x* 的排列總數也可以快速增長,大于大多數隨機數生成器的周期。 這意味著長序列的大多數排列永遠不會產生。 例如,長度為2080的序列是可以在 Mersenne Twister 隨機數生成器的周期內擬合的最大序列。 `random.``sample`(*population*, *k*)返回從總體序列或集合中選擇的唯一元素的 *k* 長度列表。 用于無重復的隨機抽樣。 返回包含來自總體的元素的新列表,同時保持原始總體不變。 結果列表按選擇順序排列,因此所有子切片也將是有效的隨機樣本。 這允許抽獎獲獎者(樣本)被劃分為大獎和第二名獲勝者(子切片)。 總體成員不必是 [hashable](../glossary.xhtml#term-hashable) 或 unique 。 如果總體包含重復,則每次出現都是樣本中可能的選擇。 要從一系列整數中選擇樣本,請使用 [`range()`](stdtypes.xhtml#range "range") 對象作為參數。 對于從大量人群中采樣,這種方法特別快速且節省空間:`sample(range(10000000), k=60)` 。 如果樣本大小大于總體大小,則引發 [`ValueError`](exceptions.xhtml#ValueError "ValueError") 。 ## 實值分布 以下函數生成特定的實值分布。如常用數學實踐中所使用的那樣, 函數參數以分布方程中的相應變量命名;大多數這些方程都可以在任何統計學教材中找到。 `random.``random`()返回 \[0.0, 1.0) 范圍內的下一個隨機浮點數。 `random.``uniform`(*a*, *b*)返回一個隨機浮點數 *N* ,當 `a <= b` 時 `a <= N <= b` ,當 `b < a` 時 `b <= N <= a` 。 取決于等式 `a + (b-a) * random()` 中的浮點舍入,終點 `b` 可以包括或不包括在該范圍內。 `random.``triangular`(*low*, *high*, *mode*)返回一個隨機浮點數 *N* ,使得 `low <= N <= high` 并在這些邊界之間使用指定的 *mode* 。 *low* 和 *high* 邊界默認為零和一。 *mode* 參數默認為邊界之間的中點,給出對稱分布。 `random.``betavariate`(*alpha*, *beta*)Beta 分布。 參數的條件是 `alpha > 0` 和 `beta > 0`。 返回值的范圍介于 0 和 1 之間。 `random.``expovariate`(*lambd*)指數分布。 *lambd* 是 1.0 除以所需的平均值,它應該是非零的。 (該參數本應命名為 “lambda” ,但這是 Python 中的保留字。)如果 *lambd* 為正,則返回值的范圍為 0 到正無窮大;如果 *lambd* 為負,則返回值從負無窮大到 0。 `random.``gammavariate`(*alpha*, *beta*)Gamma 分布。 ( *不是* gamma 函數! ) 參數的條件是 `alpha > 0` 和 `beta > 0`。 概率分布函數是: ``` x ** (alpha - 1) * math.exp(-x / beta) pdf(x) = -------------------------------------- math.gamma(alpha) * beta ** alpha ``` `random.``gauss`(*mu*, *sigma*)高斯分布。 *mu* 是平均值,*sigma* 是標準差。 這比下面定義的 [`normalvariate()`](#random.normalvariate "random.normalvariate") 函數略快。 `random.``lognormvariate`(*mu*, *sigma*)對數正態分布。 如果你采用這個分布的自然對數,你將得到一個正態分布,平均值為 *mu* 和標準差為 *sigma* 。 *mu* 可以是任何值,*sigma* 必須大于零。 `random.``normalvariate`(*mu*, *sigma*)正態分布。 *mu* 是平均值,*sigma* 是標準差。 `random.``vonmisesvariate`(*mu*, *kappa*)*mu* 是平均角度,以弧度表示,介于0和 2\**pi* 之間,*kappa* 是濃度參數,必須大于或等于零。 如果 *kappa* 等于零,則該分布在0到 2\**pi* 的范圍內減小到均勻的隨機角度。 `random.``paretovariate`(*alpha*)帕累托分布。 *alpha* 是形狀參數。 `random.``weibullvariate`(*alpha*, *beta*)威布爾分布。 *alpha* 是比例參數,*beta* 是形狀參數。 ## 替代生成器 *class* `random.``Random`(\[*seed*\])。該類實現了 [`random`](#module-random "random: Generate pseudo-random numbers with various common distributions.") 模塊所用的默認偽隨機數生成器。 *class* `random.``SystemRandom`(\[*seed*\])使用 [`os.urandom()`](os.xhtml#os.urandom "os.urandom") 函數的類,用從操作系統提供的源生成隨機數。 這并非適用于所有系統。 也不依賴于軟件狀態,序列不可重現。 因此,[`seed()`](#random.seed "random.seed") 方法沒有效果而被忽略。 [`getstate()`](#random.getstate "random.getstate") 和 [`setstate()`](#random.setstate "random.setstate") 方法如果被調用則引發 [`NotImplementedError`](exceptions.xhtml#NotImplementedError "NotImplementedError")。 ## 關于再現性的說明 有時能夠重現偽隨機數生成器給出的序列是有用的。 通過重新使用種子值,只要多個線程沒有運行,相同的序列就可以在兩次不同運行之間重現。 大多數隨機模塊的算法和種子函數都會在 Python 版本中發生變化,但保證兩個方面不會改變: - 如果添加了新的播種方法,則將提供向后兼容的播種機。 - 當兼容的播種機被賦予相同的種子時,生成器的 `random()` 方法將繼續產生相同的序列。 ## 例子和配方 基本示例: ``` >>> random() # Random float: 0.0 <= x < 1.0 0.37444887175646646 >>> uniform(2.5, 10.0) # Random float: 2.5 <= x < 10.0 3.1800146073117523 >>> 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] ``` 模擬: ``` >>> # 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 >>> # (a ten, jack, queen, or king). >>> deck = collections.Counter(tens=16, low_cards=36) >>> seen = sample(list(deck.elements()), k=20) >>> seen.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(10000)) / 10000 0.4169 >>> # Probability of the median of 5 samples being in middle two quartiles >>> def trial(): ... return 2500 <= sorted(choices(range(10000), k=5))[2] < 7500 ... >>> sum(trial() for i in range(10000)) / 10000 0.7958 ``` [statistical bootstrapping](https://en.wikipedia.org/wiki/Bootstrapping_(statistics)) \[https://en.wikipedia.org/wiki/Bootstrapping\_(statistics)\] 使用重采樣和替換來估計大小為五的樣本的均值的置信區間的示例: ``` # http://statistics.about.com/od/Applications/a/Example-Of-Bootstrapping.htm from statistics import mean from random import choices data = 1, 2, 4, 4, 10 means = sorted(mean(choices(data, k=5)) for i in range(20)) print(f'The sample mean of {mean(data):.1f} has a 90% confidence ' f'interval from {means[1]:.1f} to {means[-2]:.1f}') ``` 使用 [重新采樣排列測試](https://en.wikipedia.org/wiki/Resampling_(statistics)#Permutation_tests) \[https://en.wikipedia.org/wiki/Resampling\_(statistics)#Permutation\_tests\] 來確定統計學顯著性或者使用 [p-值](https://en.wikipedia.org/wiki/P-value) \[https://en.wikipedia.org/wiki/P-value\] 來觀察藥物與安慰劑的作用之間差異的示例: ``` # Example from "Statistics is Easy" by Dennis Shasha and Manda Wilson from statistics import 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 = 10000 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.') ``` 模擬單個服務器隊列中的到達時間和服務交付: ``` from random import expovariate, gauss from statistics import mean, median, stdev average_arrival_interval = 5.6 average_service_time = 5.0 stdev_service_time = 0.5 num_waiting = 0 arrivals = [] starts = [] arrival = service_end = 0.0 for i in range(20000): if arrival <= service_end: num_waiting += 1 arrival += expovariate(1.0 / average_arrival_interval) arrivals.append(arrival) else: num_waiting -= 1 service_start = service_end if num_waiting else arrival service_time = gauss(average_service_time, stdev_service_time) service_end = service_start + service_time starts.append(service_start) waits = [start - arrival for arrival, start in zip(arrivals, starts)] print(f'Mean wait: {mean(waits):.1f}. Stdev wait: {stdev(waits):.1f}.') print(f'Median wait: {median(waits):.1f}. Max wait: {max(waits):.1f}.') ``` 參見 [Statistics for Hackers](https://www.youtube.com/watch?v=Iq9DzN6mvYA) \[https://www.youtube.com/watch?v=Iq9DzN6mvYA\] [Jake Vanderplas](https://us.pycon.org/2016/speaker/profile/295/) \[https://us.pycon.org/2016/speaker/profile/295/\] 撰寫的視頻教程,使用一些基本概念進行統計分析,包括模擬、抽樣、改組和交叉驗證。 [Economics Simulation](http://nbviewer.jupyter.org/url/norvig.com/ipython/Economics.ipynb) \[http://nbviewer.jupyter.org/url/norvig.com/ipython/Economics.ipynb\] [Peter Norvig](http://norvig.com/bio.html) \[http://norvig.com/bio.html\] 編寫的市場模擬,顯示了該模塊提供的許多工具和分布的有效使用(高斯、均勻、樣本、beta變量、選擇、三角和隨機范圍等)。 [A Concrete Introduction to Probability (using Python)](http://nbviewer.jupyter.org/url/norvig.com/ipython/Probability.ipynb) \[http://nbviewer.jupyter.org/url/norvig.com/ipython/Probability.ipynb\] [Peter Norvig](http://norvig.com/bio.html) \[http://norvig.com/bio.html\] 撰寫的教程,涵蓋了概率論基礎知識,如何編寫模擬,以及如何使用 Python 進行數據分析。 ### 導航 - [索引](../genindex.xhtml "總目錄") - [模塊](../py-modindex.xhtml "Python 模塊索引") | - [下一頁](statistics.xhtml "statistics --- Mathematical statistics functions") | - [上一頁](fractions.xhtml "fractions --- 分數") | - ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png) - [Python](https://www.python.org/) ? - zh\_CN 3.7.3 [文檔](../index.xhtml) ? - [Python 標準庫](index.xhtml) ? - [數字和數學模塊](numeric.xhtml) ? - $('.inline-search').show(0); | ? [版權所有](../copyright.xhtml) 2001-2019, Python Software Foundation. Python 軟件基金會是一個非盈利組織。 [請捐助。](https://www.python.org/psf/donations/) 最后更新于 5月 21, 2019. [發現了問題](../bugs.xhtml)? 使用[Sphinx](http://sphinx.pocoo.org/)1.8.4 創建。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看