我正在尝试在 Python 3(使用 Windows 7)上运行其他人的 Python 2 程序。它的目的是生成大的阶乘,然后将它们用作随机数流。该程序将十进制阶乘转换为从 0 到 255 的字节值,并将 chr(byte value) 写入文件。它通过移动 8 位小数部分的阶乘来计算每个字节。但是,编码从 Python 2 更改为 3(我不确定到底是什么或为什么重要),并且 chr() 命令不适用于 128 到 159 的任何值(但值 160 到 255 有效)-程序引发“UnicodeEncodeError: 'charmap' codec can't encode character '(the character point)' in position 0: character maps to <undefined>”
我已经尝试使用“open(filename, "w", encoding="utf-8")”更改文件编码,这成功地写入了所有字节。但是,当我测试文件的随机性属性时,它们比作者得到的结果要差得多。
我应该更改什么来存储字符字节而不影响数据的随机性?
测试程序称为“ent”。在命令提示符下,它以一个文件作为参数,然后输出一些随机性统计信息。如需了解更多信息,请访问其网站 http://www.fourmilab.ch/random/。
我使用
open(filename, "w", encoding="utf-8")对 !500,000 文件的输入结果:Entropy = 6.251272 bits per byte. Optimum compression would reduce the size of this 471812 byte file by 21 percent. Chi square distribution for 471812 samples is 6545600.65, and randomly would exceed this value less than 0.01 percent of the times. Arithmetic mean value of data bytes is 138.9331 (127.5 = random). Monte Carlo value for Pi is 3.173294335 (error 1.01 percent). Serial correlation coefficient is 0.162915 (totally uncorrelated = 0.0).作者对 !500,000 文件的输入结果:
Entropy = 7.999373 bits per byte. Optimum compression would reduce the size of this 313417 byte file by 0 percent. Chi square distribution for 31347 samples is 272.63, and randomly would exceed this value 25.00 percent of the times. Arithmetic mean value of data bytes is 127.6336 (127.5 = random). Monte Carlo value for Pi is 3.149475458 (error 0.25 percent). Serial correlation coefficient is -0.001209 (totally uncorrelated = 0.0).
请您参考如下方法:
看起来 timakro 有答案(谢谢):
“要写入二进制文件,您应该以二进制模式打开它 open(filename, "wb") 并向其写入类似字节的对象。例如写入值为 123 的字节:file.write(bytes ([123]))。” -蒂马克罗
当我将“bytes([byte value from 0-255])”写入文件时,它获得了 ent 程序预期的随机分数。因此,我将 Python 2 的 chr() 更改为 bytes(),以便程序在 Python 3 中存储字节。不需要字符编码。
