How to set the precision on str(numpy.float64)?
You can just use standard string formatting:
>>> x = 1.2345678
>>> '%.2f' % x
'1.23'
How to set precision of numpy float array when converting from string array?
Convert the the strings to float128
.
Try this:
import numpy as np
strarray = ["535.","535.","534.68"]
floatarray = np.array(filter(None,strarray),dtype='|S10').astype(np.float128)
print floatarray
Output:
[ 535.0 535.0 534.68]
Or use the recommended longdouble
:
import numpy as np
strarray = ["535.","535.","534.68"]
floatarray = np.array(filter(None,strarray),dtype='|S10').astype(np.longdouble)
print floatarray
Output:
[ 535.0 535.0 534.68]
Formatting floats in a numpy array
In order to make numpy display float arrays in an arbitrary format, you can define a custom function that takes a float value as its input and returns a formatted string:
In [1]: float_formatter = "{:.2f}".format
The f
here means fixed-point format (not 'scientific'), and the .2
means two decimal places (you can read more about string formatting here).
Let's test it out with a float value:
In [2]: float_formatter(1.234567E3)
Out[2]: '1234.57'
To make numpy print all float arrays this way, you can pass the formatter=
argument to np.set_printoptions
:
In [3]: np.set_printoptions(formatter={'float_kind':float_formatter})
Now numpy will print all float arrays this way:
In [4]: np.random.randn(5) * 10
Out[4]: array([5.25, 3.91, 0.04, -1.53, 6.68]
Note that this only affects numpy arrays, not scalars:
In [5]: np.pi
Out[5]: 3.141592653589793
It also won't affect non-floats, complex floats etc - you will need to define separate formatters for other scalar types.
You should also be aware that this only affects how numpy displays float values - the actual values that will be used in computations will retain their original precision.
For example:
In [6]: a = np.array([1E-9])
In [7]: a
Out[7]: array([0.00])
In [8]: a == 0
Out[8]: array([False], dtype=bool)
numpy prints a
as if it were equal to 0
, but it is not - it still equals 1E-9
.
If you actually want to round the values in your array in a way that affects how they will be used in calculations, you should use np.round
, as others have already pointed out.
Formatting numpy float values
You can define a custom function:
>>> myformat = lambda x: "%.3f" % x
>>> myformat(8.928571429999999509e+02)
'892.857'
Difference in precision in np.float64 and python float (64)
As mentioned by @hpaulj in comments, it is not calculation precision. It is printing. Add this line to your code to see the precision you would like while printing in numpy:
np.set_printoptions(precision=16)
output of your code after above line:
dist1: [0.6858955910000049]
dist [0.6858955910000049]
Convert floating point number to a certain precision, and then copy to string
With Python < 3 (e.g. 2.6 [see comments] or 2.7), there are two ways to do so.
# Option one
older_method_string = "%.9f" % numvar
# Option two
newer_method_string = "{:.9f}".format(numvar)
But note that for Python versions above 3 (e.g. 3.2 or 3.3), option two is preferred.
For more information on option two, I suggest this link on string formatting from the Python documentation.
And for more information on option one, this link will suffice and has info on the various flags.
Python 3.6 (officially released in December of 2016), added the f
string literal, see more information here, which extends the str.format
method (use of curly braces such that f"{numvar:.9f}"
solves the original problem), that is,
# Option 3 (versions 3.6 and higher)
newest_method_string = f"{numvar:.9f}"
solves the problem. Check out @Or-Duan's answer for more info, but this method is fast.
Related Topics
Matplotlib Rotate Image File by X Degrees
How to Increment a Variable on a for Loop in Jinja Template
Missing 1 Required Positional Argument - Issue
Python - Using Regex to Find Multiple Matches and Print Them Out
How to Extract Data from Dictionary in the List
How to Use and Print the Pandas Dataframe Name
How to Get Rid of the B-Prefix in a String in Python
Running Two Python Scripts With Bash File
Django.Db.Utils.Operationalerror: (1045, Access Denied for User '<User>'@'Localhost'
Numpy Distance Calculations of Different Shaped Arrays
Stripping Non Printable Characters from a String in Python
How to Extract Address from Raw Text Using Nltk in Python
Adding Months to a Pandas Object in Python
How to Append New Data Onto a New Line
How to Randomly Partition a List into N Nearly Equal Parts