user2329125
user2329125

Reputation:

Use pythons complex type in numpy-array

For example when I do this:

In : b = 0.05 + 0j
In : b
Out: (0.05+0j)
In : type(b)
Out: complex

Okay as expected. Now if I do this inside an numpy-array:

In : a = numpy.array([0,0,0], dtype = complex)
In : a[1] = 0.05
In : a[1]
Out: (0.050000000000000002775557561563+0.j)
In : type(a[1])
Out: numpy.complex128

I obviously do not want that precision loss, what can I do to prevent this behaviour? Or is there nothing I can do when I want to stay with numpy?

Upvotes: 0

Views: 397

Answers (1)

Rory Yorke
Rory Yorke

Reputation: 2236

There's no loss of precision; 0.05 = 5/100 isn't precisely representable in binary floating point (the denominator should be a power of 2 to allow precise representation).

Perhaps more convincing is the output of this

import numpy
b = 0.05 + 0j
a = numpy.array((b, ))
print(b, a[0])
print(b == a[0])
print('%.17g' % b.real)

which is

((0.05+0j), (0.050000000000000003+0j))
True
0.050000000000000003

(Ubuntu 14.04, Python 2.7.6, Numpy 1.8.2)

Upvotes: 1

Related Questions