Home > other >  Why is the precision of numpy output different each time?
Why is the precision of numpy output different each time?

Time:01-22

Run the following program:

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

We have the result:

0.4418517709510906
0.05536715253773261
0.44633855235431785
0.3143041997189251
0.16175184090609163
0.8822875281567105
0.11367473012241913
0.9951703577237277
0.009103257465210124
0.5185580156093157

Why is the precision of each output different? Sometimes accurate to 16 decimal places, but sometimes accurate to 18 decimal places. Why does this happen?

Also, if I want to control the precision of the output, i.e., only 15 decimal places are output each time, how can I do this?


Edit: I try to use np.set_printoptions(precision=15)

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

But the output is:

0.3908531691561824
0.6363290508517755
0.3484260990246082
0.23792451272035053
0.5776808805593472
0.3631616619602701
0.878754651138258
0.6266540814279749
0.8309347174000745
0.5763464514883537

This still doesn't get the result I want. The result I want is something like below:

0.390853169156182
0.636329050851775
0.348426099024608
0.237924512720350
0.577680880559347
0.363161661960270
0.878754651138258
0.626654081427974
0.830934717400074
0.576346451488353

CodePudding user response:

print(a) prints the shortest numeric string that yields the same float64 value as a.

Example:

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)

Result:

0.392820481778549002 0x3fd923f8849c0570
0.392820481778549002 0x3fd923f8849c0570
True

You can use the f"{a:.18f}" syntax to get fixed-width output. The equivalent for numpy arrays is np.set_printoptions(precision=18, floatmode="fixed").

  •  Tags:  
  • Related