高精度打印numpy.float64 [英] Printing numpy.float64 with full precision
问题描述
打印numpy.float64并将其转换为字符串的正确/可接受的方法是什么?我注意到仅使用print
或str()
会损失一些精度.但是,repr
保持完整精度.例如:
What is the proper/accepted way to print and convert a numpy.float64 to a string? I've noticed just using print
or str()
will lose some precision. However, repr
maintains the full precision. For example:
>>> import numpy
>>> print numpy.float64('6374.345407799015')
6374.3454078
>>> print repr(numpy.float64('6374.345407799015'))
6374.3454077990154
-
我假设仅调用print就会转换为对float64对象的调用
str()
.那么numpy.float64的__str__()
是用'%s' % (float(self))
之类实现的还是用Python内置的float()
强制将float64转换?为此,我试图快速查看numpy来源,但并没有立即发现正在发生的事情.
I assume that just calling print turns into calling
str()
on the float64 object. So is__str__()
for numpy.float64 implemented with something like'%s' % (float(self))
or somehow casts the float64 with Python's built-infloat()
? I tried to quickly look around the numpy source for this but wasn't immediately obvious what was happening.
我一直认为repr()
应该返回有效的Python代码,而eval()
可以使用该代码重新创建对象.这是公认的惯例吗?幸运的是,在这种情况下,numpy没有遵循此约定,因为repr()
仅将原始数字作为字符串而不是像"numpy.float64('6374.345407799015')"
这样的字符串返回.
I've always thought repr()
should return valid Python code that could be used by eval()
to re-create the object. Is this an accepted convention? Luckily in this case numpy does not follow this convention because repr()
returns just the raw number as a string instead of something like "numpy.float64('6374.345407799015')"
.
因此,所有这些使我感到困惑.将numpy.float64转换为字符串和/或打印它同时又确保始终具有相同的全精度的正确方法是什么?
So, all of this confuses me. What is the correct way to convert a numpy.float64 to a string and/or print it while guaranteeing you always have the same, full precision?
推荐答案
astype
方法效果很好:
>>> numpy.float64('6374.345407799015').astype(str)
'6374.345407799015'
这篇关于高精度打印numpy.float64的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!