Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the precision on str(numpy.float64)?

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

like image 408
Fookatchu Avatar asked Jan 30 '11 19:01

Fookatchu


People also ask

How precise is Numpy?

In normal numpy use, the numbers are double. Which means that the accuracy will be less than 16 digits.

What is float64 in Python?

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).

Does Numpy Use single or double precision?

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.

What is the difference between float and Numpy float64?

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.


1 Answers

You can just use standard string formatting:

>>> x = 1.2345678
>>> '%.2f' % x
'1.23'
like image 111
David Heffernan Avatar answered Oct 27 '22 12:10

David Heffernan