为什么每次numpy输出的精度都不一样?
Why is the precision of numpy output different each time?
运行以下程序:
for i in range(10):
a = np.random.uniform(0, 1)
print(a)
我们有结果:
0.4418517709510906
0.05536715253773261
0.44633855235431785
0.3143041997189251
0.16175184090609163
0.8822875281567105
0.11367473012241913
0.9951703577237277
0.009103257465210124
0.5185580156093157
为什么每次输出的精度都不一样?有时精确到小数点后 16 位,但有时精确到小数点后 18 位。 为什么会这样?
另外,如果我想控制输出的精度,即每次只输出小数点后15位,怎么办?
编辑: 我尝试使用 np.set_printoptions(precision=15)
np.set_printoptions(precision=15)
for i in range(10):
a = np.random.uniform(0, 1)
print(a)
但是输出是:
0.3908531691561824
0.6363290508517755
0.3484260990246082
0.23792451272035053
0.5776808805593472
0.3631616619602701
0.878754651138258
0.6266540814279749
0.8309347174000745
0.5763464514883537
这样还是没有得到我想要的结果。我想要的结果如下所示:
0.390853169156182
0.636329050851775
0.348426099024608
0.237924512720350
0.577680880559347
0.363161661960270
0.878754651138258
0.626654081427974
0.830934717400074
0.576346451488353
print(a)
打印产生与 a
.
相同的 float64 值的最短数字字符串
示例:
a = 0.392820481778549002
b = 0.392820481778549
a_bits = np.asarray(a).view(np.int64).item()
b_bits = np.asarray(b).view(np.int64).item()
print(f"{a:.18f}", hex(a_bits))
print(f"{b:.18f}", hex(b_bits))
print(a == b)
结果:
0.392820481778549002 0x3fd923f8849c0570
0.392820481778549002 0x3fd923f8849c0570
True
您可以使用 f"{a:.18f}"
语法来获得 fixed-width 输出。 numpy 数组的等价物是 np.set_printoptions(precision=18, floatmode="fixed")
.
运行以下程序:
for i in range(10):
a = np.random.uniform(0, 1)
print(a)
我们有结果:
0.4418517709510906
0.05536715253773261
0.44633855235431785
0.3143041997189251
0.16175184090609163
0.8822875281567105
0.11367473012241913
0.9951703577237277
0.009103257465210124
0.5185580156093157
为什么每次输出的精度都不一样?有时精确到小数点后 16 位,但有时精确到小数点后 18 位。 为什么会这样?
另外,如果我想控制输出的精度,即每次只输出小数点后15位,怎么办?
编辑: 我尝试使用 np.set_printoptions(precision=15)
np.set_printoptions(precision=15)
for i in range(10):
a = np.random.uniform(0, 1)
print(a)
但是输出是:
0.3908531691561824
0.6363290508517755
0.3484260990246082
0.23792451272035053
0.5776808805593472
0.3631616619602701
0.878754651138258
0.6266540814279749
0.8309347174000745
0.5763464514883537
这样还是没有得到我想要的结果。我想要的结果如下所示:
0.390853169156182
0.636329050851775
0.348426099024608
0.237924512720350
0.577680880559347
0.363161661960270
0.878754651138258
0.626654081427974
0.830934717400074
0.576346451488353
print(a)
打印产生与 a
.
示例:
a = 0.392820481778549002
b = 0.392820481778549
a_bits = np.asarray(a).view(np.int64).item()
b_bits = np.asarray(b).view(np.int64).item()
print(f"{a:.18f}", hex(a_bits))
print(f"{b:.18f}", hex(b_bits))
print(a == b)
结果:
0.392820481778549002 0x3fd923f8849c0570
0.392820481778549002 0x3fd923f8849c0570
True
您可以使用 f"{a:.18f}"
语法来获得 fixed-width 输出。 numpy 数组的等价物是 np.set_printoptions(precision=18, floatmode="fixed")
.