Hướng dẫn how does random random work in python? - làm thế nào để ngẫu nhiên ngẫu nhiên hoạt động 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 random work in python? - làm thế nào để ngẫu nhiên ngẫu nhiên hoạt động 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)

Ngẫu nhiên làm ngẫu nhiên trong Python?

Phương thức ngẫu nhiên ngẫu nhiên () Phương thức ngẫu nhiên () Phương thức trả về một số nổi ngẫu nhiên trong khoảng từ 0 đến 1.returns a random floating number between 0 and 1.

Làm thế nào để hàm ngẫu nhiên ngẫu nhiên () hoạt động?

Các chức năng trong mô-đun ngẫu nhiên dựa vào hàm tạo số giả ngẫu nhiên (), tạo ra số float ngẫu nhiên trong khoảng 0,0 đến 1,0.Các loại chức năng cụ thể này được sử dụng trong rất nhiều trò chơi, xổ số hoặc bất kỳ ứng dụng nào yêu cầu tạo số ngẫu nhiên.generates a random float number between 0.0 and 1.0. These particular type of functions is used in a lot of games, lotteries, or any application requiring a random number generation.

Làm thế nào để Python ngẫu nhiên tạo ra các số ngẫu nhiên?

Các giá trị số nguyên ngẫu nhiên có thể được tạo với hàm randint ().Hàm này có hai đối số: bắt đầu và kết thúc phạm vi cho các giá trị số nguyên được tạo.Các số nguyên ngẫu nhiên được tạo ra trong và bao gồm bắt đầu và kết thúc các giá trị phạm vi, cụ thể là trong khoảng [bắt đầu, kết thúc].with the randint() function. This function takes two arguments: the start and the end of the range for the generated integer values. Random integers are generated within and including the start and end of range values, specifically in the interval [start, end].

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

Mô -đun ngẫu nhiên của Python cung cấp hàm mẫu () để lấy mẫu ngẫu nhiên, chọn ngẫu nhiên nhiều hơn một phần tử từ danh sách mà không lặp lại các phần tử.Nó trả về một danh sách các mục duy nhất được chọn ngẫu nhiên từ danh sách, trình tự hoặc bộ.Chúng tôi gọi nó là lấy mẫu ngẫu nhiên mà không cần thay thế.randomly picking more than one element from the list without repeating elements. It returns a list of unique items chosen randomly from the list, sequence, or set. We call it random sampling without replacement.