有关float类型表示范围的探究

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# -*- encoding: utf-8 -*-

import random
from matplotlib import pyplot as plt


def main():
# 从000000开始到 00001101010....,二进制递增顺序查看对应的float表示范围
# for i in range(1000000):
# binStr = str(bin(i))[2:]
# binStr = "0" * (32 - len(binStr)) + binStr
# print(binStr)
# print(strToFloat32(binStr))

# print(strToFloat32("11111111111111111111111111111111"))
# print(strToFloat32("11111111111111111111111111111110"))
# print(strToFloat32("11111111111111111111111111111101"))
# print(strToFloat32("11111111111111111111111111111100"))
# print(strToFloat32("11111111111111111111111111111001"))

arr = []
for i in range(10000):
arr.append(randFloat32())
minNum = min(arr)
maxNum = max(arr)
print(minNum, maxNum)
div = 50 # 把这一整段区间分成很多段,分别看每一段包含的数量
partLen = (maxNum - minNum) / div
y = []
x = []
for i in range(div):
left = minNum + partLen * i
count = 0
for n in arr:
if left <= n < left + partLen:
count += 1
y.append(count)
x.append(f"{int(left)}")
print(f"{count} /t/t{int(left)}~{int(left + partLen)}", )

plt.plot(x, y)
plt.xticks(x, rotation=45)
plt.show()
...


def strBinToInt(string):
return eval(f"0b{string}")


def strToFloat32(string):
"""把一个32位二进制字符流解析成float类型"""
# 解析二进制字符流
flag = string[0]
head = string[1:9]
tile = string[9:]
headNumber = strBinToInt(head)
tile = "1" + tile
left = strBinToInt(tile[:headNumber + 1])
right = 0.0
rightStr = tile[headNumber + 1:]
for i, char in enumerate(rightStr):
if char == "1":
right += 0.5 ** i
...
if flag == "0":
return left + right
else:
return -(left + right)


def randFloat32():
"""随机生成一个float32的浮点数"""
randStr = ""
for i in range(32):
if random.random() < 0.5:
randStr += "0"
else:
randStr += "1"
return strToFloat32(randStr)


if __name__ == '__main__':
main()