i need to write a couple of numpy floats to a csv-file which has additional string content. therefore i dont use savetxt etc. with numpy.set_printoptions() i can only define the print behaviour, but not the str() behaviour. i know that i miss something and it cant be that hard, but i dont find a reasonable answer on the interwebs. maybe someone can point me in the right direction. heres some example code:
In [1]: import numpy as np
In [2]: foo = np.array([1.22334])
In [3]: foo
Out[3]: array([ 1.22334])
In [4]: foo[0]
Out[4]: 1.2233400000000001
In [5]: str(foo[0])
Out[5]: '1.22334'
In [6]: np.set_printoptions(precision=3)
In [7]: foo
Out[7]: array([ 1.223])
In [8]: foo[0]
Out[8]: 1.2233400000000001
In [9]: str(foo[0])
Out[9]: '1.22334'
How do i convert np.float to a nicely formatted string, which i can feed to file.write()?
kind regards,
fookatchu
In normal numpy use, the numbers are double. Which means that the accuracy will be less than 16 digits.
Python float values are represented as 64-bit double-precision values. 1.8 X 10308 is an approximate maximum value for any floating-point number. If it exceeds or exceeds the max value, Python returns an error with string inf (infinity).
The bottom line is that numpy uses the default double precision floating point number, which gives you approximately 16 decimal places of precision on most 64 bit systems.
float32 and np. float64 are numpy specific 32 and 64-bit float types. Thus, when you do isinstance(2.0, np. float) , it is equivalent to isinstance(2.0, float) as 2.0 is a plain python built-in float type... and not the numpy type.
You can just use standard string formatting:
>>> x = 1.2345678
>>> '%.2f' % x
'1.23'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With