繁体   English   中英

为什么numpy output每次的精度都不一样?

[英]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

为什么每个output的精度都不一样? 有时精确到小数点后 16 位,但有时精确到小数点后 18 位。 为什么会这样?

另外,如果我想控制output的精度,即output每次只有15位小数,我该怎么做呢?


编辑:我尝试使用np.set_printoptions(precision=15)

np.set_printoptions(precision=15)
for i in range(10):
    a = np.random.uniform(0, 1)
    print(a)

但是 output 是:

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}"语法来获得固定宽度的 output。 numpy arrays 的等价物是np.set_printoptions(precision=18, floatmode="fixed")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM