数值从字符串到浮点数的转换(科学计数法)

Conversion from string to float of numerical values (scientific notation)

我正在使用 Python 读取文件并将以字符串形式写入的数值转换为浮点数。我观察到一个奇怪的转换:

 a="-5.970471694E+02"

 b = float(a)
 b
 >> -597.0471694

 bb = np.float64(a)
 bb
 >> -597.04716940000003

 e="-5.970471695E+02"
 ee = np.float64(e)
 ee
 >> -597.0471695

 ee-bb
 >> -9.9999965641472954e-08

bb末尾的“0000003”一词是什么原因造成的?为什么我没有观察到 ee 的相同情况。这真的是个问题吗?我认为这个问题是由于浮点精度引起的,但在我开始使用变量之前结果似乎受到了干扰...

float 和 float64 都使用数字的二进制表示。两者都必须保存由以 10 为底数的数字转换为以 2 为底数的数字所引起的近似值。浮点数使用较少的位,因此误差更大并且当 a 被复制到b。这是因为 b 采用 a 包括舍入误差而不丢失信息,而 a 包含 000..03 值。换句话说,就是十进制数转二进制数的舍入误差。

What is the reason of the term "0000003" at the end of bb. Why I don't observe the same thing for ee.

bbb 具有相同的值(尝试评估 b == bb)。区别在于解释器如何表示它们。默认情况下,numpy 浮点数显示为小数点后 8 位数字,而 Python 浮点数打印为 13 位有效数字(包括小数点前的数字)。

Is this really a problem?

由于 bbb 的实际值相同,所以答案几乎可以肯定是否定的。如果显示差异困扰您,您可以使用 np.set_printoptions to control how numpy floats are represented in the interpreter. If you use IPython, you can also use the %precision magic 来控制 Python 浮点数的打印方式。