Numpy精度設置

綜述

近期遇到了一個很有意思的問題,在這裏記錄一下:
一般來說我們設置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")

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章