综述
近期遇到了一个很有意思的问题,在这里记录一下:
一般来说我们设置numpy的精度:
np.round(V,decimals=6)
而我们也知道在保存txt时候,
np.savetxt(cur_dir+"/imgs/V0_.txt",V,fmt='%1.6f')
可以使用fmt
参数来设置。
但是使用这种方式:
np.savetxt(cur_dir+"/imgs/V0_.txt", np.round(V,decimals=6))
却是失败的。最后精度依然是小数点后18位(numpy保存txt默认精度)
原因
我在Github上raise了一个issue:
https://github.com/numpy/numpy/issues/16176
原因是numpy数组的数值与numpy数组表示为字符串并不是一致的。当使用savetxt时,依然会使用最初的精度来存储。
The reason is that the array values themselves are decoupled from the way that those values are represented as strings. The default value for the fmt keyword argument is %.18e, so savetxt will save values in that format by default no matter the type/precision of the underlying array elements. To save the values in a different string format, you must explicitly supply that format, e.g. np.savetxt(my_filename, np.round(my_data, decimals=6), fmt="%.6f")