7

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?

user1551817
  • 6,693
  • 22
  • 72
  • 109
  • 4
    Only printed representation are different – Grijesh Chauhan Feb 28 '13 at 18:03
  • 1
    `7.14519700e+04` expanded is `71451.9700` which is indeed just a rounded representation of `71451.9699799` – Michael Celey Feb 28 '13 at 18:08
  • possible duplicate of [Pretty-printing of numpy.array](http://stackoverflow.com/questions/2891790/pretty-printing-of-numpy-array) and [How change the float precision of matrix elements (not when viewing)](http://stackoverflow.com/questions/15110309/how-change-the-float-precision-of-matrix-elements-not-when-viewing#comment21260978_15110309) and several others... – YXD Feb 28 '13 at 18:27

2 Answers2

8

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.

Piotr99
  • 531
  • 3
  • 12
4

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]
Henry Gomersall
  • 8,434
  • 3
  • 31
  • 54