getrandbits不产生恒定长度的数字 [英] getrandbits does not produce constant length numbers

查看:115
本文介绍了getrandbits不产生恒定长度的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用python 2.6.6.我使用getrandbits(128)获得128位随机数.

I use python 2.6.6. I use getrandbits(128) to get 128 bits random numbers.

a = random.getrandbits(128)

但是,位数并不总是128.有时少于128.这是什么原因呢?有没有更稳定的库?

However, the number of bits are not always 128. Sometimes less than that. What is the reason for this? Is there any libraries that are more stable?

推荐答案

这128位中的每个位都可以为0或1;如果最左边的位为0,则您的数字将小于2 ** 127,但它们仍然是生成的.这是预料之中的,完全是正常的行为.

Each of those 128 bits can be 0 or 1; if the left-most bits are 0 your number will be smaller than 2 ** 127 but they were still generated. This is expected and perfectly normal behaviour.

如果您需要最左边的位始终为1,请改用randrange():

If you need the left-most bit to be 1, always, use randrange() instead:

a = random.randrange(1 << 127, 1 << 128)

这将生成一个保证将第一位设置为1的数字.或者,生成一个127位的数字并将其添加1 << 127:

This generates a number that is guaranteed to have the first bit set to 1. Alternatively, generate a 127 bit number and add 1 << 127 to it:

a = random.getrandbits(127) + (1 << 127)

使用format()数字将getrandbits()输出格式化为0填充的二进制文件时,您会看到此行为:

You can see this behaviour when formatting the getrandbits() output as 0-padded binary using the format() number:

>>> format(random.getrandbits(8), '08b')
'00011110'
>>> format(random.getrandbits(8), '08b')
'01000010'
>>> format(random.getrandbits(8), '08b')
'00110010'
>>> format(random.getrandbits(8), '08b')
'10101010'
>>> format(random.getrandbits(8), '08b')
'10000110'

数字是完全随机的,但有时最左边的位以0结尾.通过减少生成的1位,然后将最左边的位设置为1,您可以生成的随机值数量的一半,但是可以确保您看到所有"的位:

The numbers are perfectly random, but sometimes the left-most bits end up 0. By generating 1 bit fewer instead, and adding in the left-most bit set to 1, you half the number of random values you can generate but guarantee you see 'all' your bits:

>>> format(random.getrandbits(7) + (1 << 8), '08b')
'100010110'
>>> format(random.getrandbits(7) + (1 << 8), '08b')
'101111101'
>>> format(random.getrandbits(7) + (1 << 8), '08b')
'101000111'
>>> format(random.getrandbits(7) + (1 << 8), '08b')
'101011111'

这完全取决于您要尝试执行的操作.

It depends entirely on what you were trying to do if this is at all desirable.

这篇关于getrandbits不产生恒定长度的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆