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:
将numpy.float64打印并转换为字符串的正确/可接受方式是什么?我注意到只使用print或str()会失去一些精度。但是,repr保持完整的精度。例如:
>>> import numpy
>>> print numpy.float64('6374.345407799015')
6374.3454078
>>> print repr(numpy.float64('6374.345407799015'))
6374.3454077990154
-
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.我假设只是调用print转而调用float64对象上的str()。 numpy.float64的__str __()是用'%s'%(float(self))实现的,或者用Python的内置float()以某种方式强制转换float64?我试图快速浏览一下numpy来源,但并不是很明显发生了什么。
-
I've always thought
repr()
should return valid Python code that could be used byeval()
to re-create the object. Is this an accepted convention? Luckily in this case numpy does not follow this convention becauserepr()
returns just the raw number as a string instead of something like"numpy.float64('6374.345407799015')"
.我一直认为repr()应该返回有效的Python代码,eval()可以使用它来重新创建对象。这是一个公认的惯例吗?幸运的是,在这种情况下,numpy不遵循这个约定,因为repr()只返回原始数字作为字符串,而不是像“numpy.float64('6374.345407799015')”。
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?
所以,所有这些让我感到困惑。将numpy.float64转换为字符串和/或打印它的正确方法是什么,同时保证始终具有相同的完全精度?
2 个解决方案
#1
8
The astype
method works well:
astype方法效果很好:
>>> numpy.float64('6374.345407799015').astype(str)
'6374.345407799015'
#2
4
Look into numpy.set_printoptions. Specifically,
查看numpy.set_printoptions。特别,
numpy.set_printoptions(precision=15)
#1
8
The astype
method works well:
astype方法效果很好:
>>> numpy.float64('6374.345407799015').astype(str)
'6374.345407799015'
#2
4
Look into numpy.set_printoptions. Specifically,
查看numpy.set_printoptions。特别,
numpy.set_printoptions(precision=15)