Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing numpy.float64 with full precision

Tags:

python

numpy

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 
  1. 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-in float()? I tried to quickly look around the numpy source for this but wasn't immediately obvious what was happening.

  2. 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')".

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?

like image 851
durden2.0 Avatar asked Oct 18 '12 13:10

durden2.0


People also ask

How do you increase the precision of a NumPy array?

If you actually want to compute the result more precisely, you could try using the np. longdouble type for your input array, which, depending on your architecture and compiler, might give you an 80- or 128-bit floating point representation, rather than the standard 64-bit np. double *.

How do you print a full float in Python?

To print float values with two decimal places in Python, use the str. format() with “{:. 2f}” as str.

How do I print a full NP array?

We can use the threshold parameter of the numpy. set_printoptions() function to sys. maxsize to print the complete NumPy array.


2 Answers

The astype method works well:

>>> numpy.float64('6374.345407799015').astype(str) '6374.345407799015' 
like image 95
Rahiel Kasim Avatar answered Sep 23 '22 18:09

Rahiel Kasim


Look into numpy.set_printoptions. Specifically,

numpy.set_printoptions(precision=15) 
like image 35
reptilicus Avatar answered Sep 22 '22 18:09

reptilicus