Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

are numpy array elements rounded automatically?

Tags:

python

numpy

I have an numpy array of floats in Python.

When I print the array, the first value is:

[7.14519700e+04, ....

If, however, I print out just the first value on it's own, the print out reads:

71451.9699799

Obviously these numbers should be identical, so I just wondered, is the array just showing me a rounded version of the element? The second number here has 12 significant figures, and the first only has 9.

I guess I just wonder why these numbers are different?

like image 443
user1551817 Avatar asked Feb 28 '13 18:02

user1551817


2 Answers

It's just in the printing, not in the storage. The only confusion might occur because the first example uses numpy's print precision settings, the second example general python's print settings.

You can adjust the numpy precision and print by

numpy.set_printoptions(precision=20)
print myarray`

(adjust precision to your needs), or select the number of significant figures in standard python formatted print:

print ('%.20f' % myarray[0])

The internal representation of the number is always the same.

like image 82
Piotr99 Avatar answered Oct 29 '22 15:10

Piotr99


The types in a numpy array are well defined. You can get how they are stored by inspecting the numpy.dtype property of an array.

For example:

import numpy
a = numpy.zeros(10)
print a.dtype

will show float64, that is a 64-bit floating point number.

You can specify the type of the array explicitly using either the commonly accepted dtype argument, or the dtype type object (that is, the thing that makes the dtype).

a = numpy.zeros(10, dtype='complex32') # a 32-bit floating point
b = numpy.longdouble(a) # create a long-double array from a

Regarding the printing, this is just a formatting issue. You can twiddle how numpy prints an array using numpy.set_printoptions:

>>> a = numpy.random.randn(3) # for interest, randn annoyingly doesn't support the dtype arg
>>> print a
[ 0.12584756  0.73540009 -0.17108244 -0.96818512]
>>> numpy.set_printoptions(precision=3)
>>> print a
[ 0.126  0.735 -0.171 -0.968]
like image 32
Henry Gomersall Avatar answered Oct 29 '22 15:10

Henry Gomersall