在Python中序列化浮点数是否安全?

时间:2018-04-20 00:27:49

标签: python pandas csv serialization floating-point

我正在通过

将Python float序列化为CSV文件
import csv

some_float = 3 / 5
csv.writerow([..., some_float, ...])

然后通过pandas.read_csv将其作为np.float64回复。是否保证我读入的浮点值将是我得到的值,或者我可能会失去一些精度?感谢。

1 个答案:

答案 0 :(得分:2)

A comment in the Python source suggests this is safe.

https://github.com/python/cpython/blob/master/Python/pystrtod.c#L828

/* The repr() precision (17 significant decimal digits) is the minimal number that is guaranteed to have enough precision so that if the number is read back in the exact same binary value is recreated. This is true for IEEE floating point by design, and also happens to work for all other modern hardware. */

Double check you are getting up to 17 significant digits in your csv file - otherwise you may need to force convert your floating point numbers with repr() on output to csv.