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
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.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')".
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?
repr()actually results in MORE precision than the original string that was used to create the float64 object in the first place. What's the story there? - durden2.0'6374.345407799015', but that can't be represented by a float64 number, so numpy (following the IEEE standard) picks the next closest thing which happens to be6374.3454077990154. - mgilsonfloat64object into a string which is full precision is to userepr. If you look at the python data-model, it recommends that__repr__for an object should provide sufficient information to reconstruct the object (if possible). - mgilsonrepr()works and that Python recommends using__repr__to reconstruct the object. However, I always thought it should return valid Python code to actually build the object. So, by this logic__repr__should return a string with the type, like my example above,"numpy.float64('6374.345407799015')". I'm glad numpy doesn't do this in this particular case. However, is my understanding of__repr__return value incorrect and why? - durden2.0