Hướng dẫn how does random work in python - ngẫu nhiên hoạt động như thế nào trong python

Mô -đun

_inst = Random()
...
random = _inst.random
3 trong Python chứa hai giao diện (lớp) của các trình tạo số giả (PRNG). Bạn có thể xem nó như hai cách để tạo số ngẫu nhiên.

  • Ngẫu nhiên sử dụng mersenne twister prng. Nó không an toàn về mặt mật mã uses the Mersenne Twister PRNG. It is not cryptographically secure
  • SystemRandom sử dụng tệp /dev /urandom trên các hệ thống POSIX hoặc hàm cryptgenrandom () trên các hệ thống Windows NT. Cả hai đều là PRNG an toàn về mặt mật mã. uses either the /dev/urandom file on POSIX systems or the CryptGenRandom() function on Windows NT systems. Both are Cryptographically secure PRNGs.

Một lưu ý trên mô -đun

_inst = Random()
...
random = _inst.random
4.
_inst = Random()
...
random = _inst.random
4.

Mô -đun

_inst = Random()
...
random = _inst.random
4 không thực hiện bất kỳ loại PRNG nào nhưng cung cấp các chức năng trợ giúp (điều này thật tuyệt vời vì chúng tôi không phải tự viết chúng) dựa trên SystemRandom và Os.urandom (mà SystemRandom dựa trên). Các ý kiến ​​là của tôi:not implement any type of PRNG but provides helper functions(which is awesome because we don't have to write them ourselves) based on SystemRandom and os.urandom(which SystemRandom is based upon). The comments are mine:

from random import SystemRandom
_sysrand = SystemRandom() #secrets._sysrand
randbits = _sysrand.getrandbits #secrets.randbits
choice = _sysrand.choice #secrets.choice

def randbelow(exclusive_upper_bound): #secrets.randbelow
    ...
    return _sysrand._randbelow(exclusive_upper_bound) #uses SystemRandom

def token_bytes(nbytes=None): #secrets.token_bytes
    ...
    return os.urandom(nbytes)

def token_hex(nbytes=None): #secrets.token_hex(uses token_bytes())
    ...
    return binascii.hexlify(token_bytes(nbytes)).decode('ascii')

def token_urlsafe(nbytes=None): # secrets.token_urlsafe(uses token_bytes())
    ...
    tok = token_bytes(nbytes)
    return base64.urlsafe_b64encode(tok).rstrip(b'=').decode('ascii')

Làm thế nào để Random.random () hoạt động?

Random.random () được xác định trong mô -đun 'ngẫu nhiên.py' trên dòng 749 (đối với tôi)

_inst = Random()
...
random = _inst.random

Lớp

_inst = Random()
...
random = _inst.random
6 không xác định phương pháp
_inst = Random()
...
random = _inst.random
7 mỗi se nhưng kế thừa ____ 18 (xác định một phương thức gọi là
_inst = Random()
...
random = _inst.random
7), là một lớp gọi là
static PyObject *
_random_Random_random_impl(RandomObject *self)
{
    uint32_t a=genrand_int32(self)>>5, b=genrand_int32(self)>>6;
    return PyFloat_FromDouble((a*67108864.0+b)*(1.0/9007199254740992.0));
}
0 nằm ở mô -đun
static PyObject *
_random_Random_random_impl(RandomObject *self)
{
    uint32_t a=genrand_int32(self)>>5, b=genrand_int32(self)>>6;
    return PyFloat_FromDouble((a*67108864.0+b)*(1.0/9007199254740992.0));
}
1.

Mã nguồn

static PyObject *
_random_Random_random_impl(RandomObject *self)
{
    uint32_t a=genrand_int32(self)>>5, b=genrand_int32(self)>>6;
    return PyFloat_FromDouble((a*67108864.0+b)*(1.0/9007199254740992.0));
}
2 của mô-đun ________ 21 (đó là mô-đun tích hợp) có thể được tìm thấy ở đây (nó thực sự được gọi là
static PyObject *
_random_Random_random_impl(RandomObject *self)
{
    uint32_t a=genrand_int32(self)>>5, b=genrand_int32(self)>>6;
    return PyFloat_FromDouble((a*67108864.0+b)*(1.0/9007199254740992.0));
}
4. Xem giải thích bên dưới)

Đặt tên quy ước cho các mô -đun Python được viết bằng C/C ++

.

Phương thức ____ 25 (hoặc

static PyObject *
_random_Random_random_impl(RandomObject *self)
{
    uint32_t a=genrand_int32(self)>>5, b=genrand_int32(self)>>6;
    return PyFloat_FromDouble((a*67108864.0+b)*(1.0/9007199254740992.0));
}
6) được định nghĩa là
static PyObject *
_random_Random_random_impl(RandomObject *self)
{
    uint32_t a=genrand_int32(self)>>5, b=genrand_int32(self)>>6;
    return PyFloat_FromDouble((a*67108864.0+b)*(1.0/9007199254740992.0));
}
7 trong tệp
static PyObject *
_random_Random_random_impl(RandomObject *self)
{
    uint32_t a=genrand_int32(self)>>5, b=genrand_int32(self)>>6;
    return PyFloat_FromDouble((a*67108864.0+b)*(1.0/9007199254740992.0));
}
4.

static PyObject *
_random_Random_random_impl(RandomObject *self)
{
    uint32_t a=genrand_int32(self)>>5, b=genrand_int32(self)>>6;
    return PyFloat_FromDouble((a*67108864.0+b)*(1.0/9007199254740992.0));
}

static PyObject *
_random_Random_random_impl(RandomObject *self)
{
    uint32_t a=genrand_int32(self)>>5, b=genrand_int32(self)>>6;
    return PyFloat_FromDouble((a*67108864.0+b)*(1.0/9007199254740992.0));
}
9 là một hàm được xác định bởi triển khai PRNG của Mersenne Twister trả về số 4 byte.

SystemRandom (). Random () hoạt động như thế nào?

.

Tôi đã làm cho hình ảnh này như một cái nhìn tổng quan về câu trả lời của tôi (tuy nhiên, tôi khuyến khích bạn đọc tất cả)

Hướng dẫn how does random work in python - ngẫu nhiên hoạt động như thế nào trong python

 ...
 def random(self):
    """Get the next random number in the range [0.0, 1.0)."""
    return (int.from_bytes(_urandom(7), 'big') >> 3) * RECIP_BPF**strong text**
0 được xác định trong mô -đun
 ...
 def random(self):
    """Get the next random number in the range [0.0, 1.0)."""
    return (int.from_bytes(_urandom(7), 'big') >> 3) * RECIP_BPF**strong text**
1.

 ...
 def random(self):
    """Get the next random number in the range [0.0, 1.0)."""
    return (int.from_bytes(_urandom(7), 'big') >> 3) * RECIP_BPF**strong text**

Hàm sử dụng một hàm khác gọi là urandom () được xác định trong mô -đun

 ...
 def random(self):
    """Get the next random number in the range [0.0, 1.0)."""
    return (int.from_bytes(_urandom(7), 'big') >> 3) * RECIP_BPF**strong text**
2

from os import urandom as _urandom

Mô-đun

 ...
 def random(self):
    """Get the next random number in the range [0.0, 1.0)."""
    return (int.from_bytes(_urandom(7), 'big') >> 3) * RECIP_BPF**strong text**
2 không xác định chức năng
 ...
 def random(self):
    """Get the next random number in the range [0.0, 1.0)."""
    return (int.from_bytes(_urandom(7), 'big') >> 3) * RECIP_BPF**strong text**
4 nhưng nhập nó từ một mô-đun tích hợp.
 ...
 def random(self):
    """Get the next random number in the range [0.0, 1.0)."""
    return (int.from_bytes(_urandom(7), 'big') >> 3) * RECIP_BPF**strong text**
2 sẽ nhập mô-đun tích hợp
 ...
 def random(self):
    """Get the next random number in the range [0.0, 1.0)."""
    return (int.from_bytes(_urandom(7), 'big') >> 3) * RECIP_BPF**strong text**
6 nếu bạn đang sử dụng hệ điều hành POSIX hoặc mô-đun tích hợp
 ...
 def random(self):
    """Get the next random number in the range [0.0, 1.0)."""
    return (int.from_bytes(_urandom(7), 'big') >> 3) * RECIP_BPF**strong text**
7 nếu bạn đang sử dụng hệ điều hành Windows NT. Các mô -đun này chứa định nghĩa cho urandom ().

if 'posix' in _names:
    name = 'posix'
    linesep = '\n'
    from posix import *

HOẶC

elif 'nt' in _names:
    name = 'nt'
    linesep = '\r\n'
    from nt import *

 ...
 def random(self):
    """Get the next random number in the range [0.0, 1.0)."""
    return (int.from_bytes(_urandom(7), 'big') >> 3) * RECIP_BPF**strong text**
6 và
 ...
 def random(self):
    """Get the next random number in the range [0.0, 1.0)."""
    return (int.from_bytes(_urandom(7), 'big') >> 3) * RECIP_BPF**strong text**
7 là các mô-đun tích hợp, vì vậy chúng không có thuộc tính
from os import urandom as _urandom
0.

Lặn trong mã nguồn:

Posix

  •  ...
     def random(self):
        """Get the next random number in the range [0.0, 1.0)."""
        return (int.from_bytes(_urandom(7), 'big') >> 3) * RECIP_BPF**strong text**
    
    4 được định nghĩa trong
    from os import urandom as _urandom
    
    2 là OS_URANDOM_IMPL () gọi _PyOS_URANDOM ().
static PyObject *
os_urandom_impl(PyObject *module, Py_ssize_t size)
{
  ...
  bytes = PyBytes_FromStringAndSize(NULL, size);
  ...
  result = _PyOS_URandom(PyBytes_AS_STRING(bytes), PyBytes_GET_SIZE(bytes));
  ...
  return bytes
}
  • from os import urandom as _urandom
    
    3 được xác định trong tệp
    from os import urandom as _urandom
    
    4 sau đó gọi pyurandom ()
int
_PyOS_URandom(void *buffer, Py_ssize_t size)
{
    return pyurandom(buffer, size, 1, 1);
}
  • from os import urandom as _urandom
    
    5 được xác định trong tệp
    from os import urandom as _urandom
    
    4 sau đó gọi dev_urandom ().
static int
pyurandom(void *buffer, Py_ssize_t size, int blocking, int raise)
{
  ...
  return dev_urandom(buffer, size, raise);
  ...
}
  • from os import urandom as _urandom
    
    7 được xác định trong tệp
    from os import urandom as _urandom
    
    4 sau đó sử dụng thư mục
    from os import urandom as _urandom
    
    9 để nhận các byte ngẫu nhiên.
_inst = Random()
...
random = _inst.random
0

Windows NT

Nó có thể trông hơi kỳ lạ (tôi cũng nghĩ rằng) nhưng tệp

from os import urandom as _urandom
2 cũng được sử dụng cho các hệ thống NT, đây là một trích dẫn (nhận xét) từ đầu tệp

Tệp này cũng được sử dụng cho Windows NT/MS-win. Trong trường hợp đó, mô -đun thực sự tự gọi mình là 'NT', không phải 'POSIX' và một vài chức năng không được thực hiện hoặc được thực hiện khác nhau. Nguồn giả định rằng đối với Windows NT, macro 'MS_Windows' được xác định độc lập với trình biên dịch được sử dụng. Các trình biên dịch khác nhau xác định macro thử nghiệm tính năng của riêng họ, ví dụ: '_Msc_ver'.
module actually calls itself 'nt', not 'posix', and a few functions are either unimplemented or implemented differently. The source
assumes that for Windows NT, the macro 'MS_WINDOWS' is defined independent of the compiler used. Different compilers define their own feature test macro, e.g. '_MSC_VER'.

Đối với Windows NT, chuỗi cuộc gọi hàm giống như đối với POSIX cho đến khi hàm pyurandom ()

  • from os import urandom as _urandom
    
    5 được xác định trong tệp
    from os import urandom as _urandom
    
    4 sau đó gọi win32_urandom ().
_inst = Random()
...
random = _inst.random
1
  • if 'posix' in _names:
        name = 'posix'
        linesep = '\n'
        from posix import *
    
    3 được xác định trong tệp
    from os import urandom as _urandom
    
    4 sau đó gọi
    if 'posix' in _names:
        name = 'posix'
        linesep = '\n'
        from posix import *
    
    5.
_inst = Random()
...
random = _inst.random
2
  • if 'posix' in _names:
        name = 'posix'
        linesep = '\n'
        from posix import *
    
    5 được khai báo trong tệp
    if 'posix' in _names:
        name = 'posix'
        linesep = '\n'
        from posix import *
    
    7 và được xác định trong thư viện
    if 'posix' in _names:
        name = 'posix'
        linesep = '\n'
        from posix import *
    
    8 và
    if 'posix' in _names:
        name = 'posix'
        linesep = '\n'
        from posix import *
    
    9 (các tệp này được cung cấp bởi Microsoft)

Làm thế nào để Python tạo ra dữ liệu ngẫu nhiên?

Nhập ngẫu nhiên n = ngẫu nhiên.ngẫu nhiên () in (n).
Nhập ngẫu nhiên n = ngẫu nhiên.randint (0,22) in (n).
Nhập RandomList RandomList = [] cho i trong phạm vi (0,5): n = ngẫu nhiên.Randint (1,30) Danh sách ngẫu nhiên.....
Nhập ngẫu nhiên #Generate 5 Số ngẫu nhiên giữa 10 đến 30 RandomList = Random.Mẫu (phạm vi (10, 30), 5) in (danh sách ngẫu nhiên).

Làm thế nào để chức năng ngẫu nhiên hoạt động?

Trình tạo số ngẫu nhiên sử dụng các công thức toán học chuyển bộ số sang một công thức khác.Ví dụ, nếu bạn lấy số N không đổi và một số N_0 khác, sau đó lấy giá trị của n mod n (toán tử modulo), bạn sẽ nhận được một số mới N_1, trông như không liên quan đến N_0.use mathematical formulas that transfer set of numbers to another one. If, for example, you take a constant number N and another number n_0 , and then take the value of n mod N (the modulo operator), you will get a new number n_1 , which looks as it if is unrelated to n_0 .

Randint ngẫu nhiên hoạt động như thế nào trong Python?

Về cơ bản, phương thức randint () trong Python trả về giá trị số nguyên ngẫu nhiên giữa hai giới hạn thấp hơn và cao hơn (bao gồm cả hai giới hạn) được cung cấp dưới dạng hai tham số.Cần lưu ý rằng phương pháp này chỉ có khả năng tạo ra giá trị ngẫu nhiên loại số nguyên.returns a random integer value between the two lower and higher limits (including both limits) provided as two parameters. It should be noted that this method is only capable of generating integer-type random value.