2016-03-02 24 views
-3

出於某種原因,我無法找到任何類型的官方文檔告訴我arc4random()的範圍是什麼。我在一些非權威的消息來源看到,它是2^32 - 1,有點超過40億。arc4random的最大回報值()

任何人都可以證實這一點嗎?如果是這樣,你能鏈接到一個正式的文件顯示這個號碼的地方?我試圖在我的iOS應用上生成一個隨機數字,並且需要有一個相當正式的高端算法才能正常工作。

+3

[此源代碼(https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man3/arc4random.3.html)是不是「專制」足夠? –

+1

通過googling'arc4random',頂部鏈接(Apple)說10秒鐘內的相同頁面*「arc4random()函數返回範圍爲0到(2 ** 32)-1」*的僞隨機數。 –

回答

0

你是正確的,

說明

The arc4random() function uses the key stream generator employed by the arc4 cipher, which uses 8*8 8 
bit S-Boxes. The S-Boxes can be in about (2**1700) states. The arc4random() function returns pseudo-random pseudorandom 
random numbers in the range of 0 to (2**32)-1, and therefore has twice the range of rand(3) and 
random(3). 

arc4random_buf()函數填充長度爲nbytes與 ARC4衍生隨機數據的區域buf中。

arc4random_uniform()將返回小於upper_bound的均勻分佈的隨機 數字。 arc4random_uniform()建議在類似`arc4random()%upper_bound'的結構上使用 ,因爲它避免了 「modulo bias」,當上限不是2的冪。

arc4random_stir()函數從/ dev/urandom讀取數據,並使用 它通過arc4random_addrandom()對S-Boxes進行置換。

有使用arc4random() 系列函數之前,不需要調用arc4random_stir(),因爲它們會自動自動matically 初始化自己。

https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man3/arc4random.3.html

+0

謝謝!我將在6分鐘內接受 –

+0

您可以在此複製粘貼中添加您自己的東西嗎?即使確定格式並強調相關短語也是一個開始。 –

3

man page for arc4random說:

arc4random()功能的範圍內返回僞隨機數0至2 - 1 ...

而,愉快地,這匹配它的返回類型uint32_t。也就是說,arc4random可能會返回任何 32位無符號整數。包含的上限是UINT32_MAX(或Swift中的UInt32.max)。

然而,如果你只需要一個特定範圍內的均勻分佈的數字,則應該使用arc4random_uniform(n)(範圍是排斥的:arc4random_uniform(5)可以返回0,1,2,3,或4)。這是更正確的 - 更方便! - 使用%來截斷由常規arc4random()返回的範圍。