Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python random.getrandbits() Method



The Python random.getrandbits() method generates a non-negative Python integer with k random bits. It is part of the Python random module, allows for the creation of random numbers with a specified bit length using the Mersenne Twister generator. This method is faster than random.randint() because it directly generates the random bits without additional processing.

To use this method, you need to import the random module as it is not accessible directly, then you need to call the method using the random object.

Syntax

Following is the syntax of random.getrandbits() function −

random.getrandbits(k)

Parameters

This method accepts a single parameter −

  • k : An integer specifying the size of the output integer.

Return Value

This method returns a non-negative Python integer with k random bits.

Example 1

Let us look at an example using python random.getrandbits() function. This example prints an integer whose binary form is 5 bits.

import random

# Generate a random number with 5 bits
print(random.getrandbits(5))

Following is the output of the code −

26

Note − You will get different random numbers each time you execute the code.

Example 2

The numbers generated by random.getrandbits() are not of constant length because the left-most bits can be zero. If you need the generated number to always have the most significant bit set to 1, you can adjust the number of bits generated or modify the number directly by setting this bit manually. Here's an example

import random

# Generate a 127-bit number and set the 128th bit to 1
random_number = random.getrandbits(127) + (1 << 127)
print(random_number)

Following is the output of the code −

327794174621992455613993598069398317009

Example 3

Here is the another example that formats the output random number as a binary string.

import random

# Generate a random number with 8 bits
random_bits = random.getrandbits(8)
print(format(random_bits, '08b'))

Following is the output of the code −

10000010
python_modules.htm
Advertisements