lash
lash

Reputation: 756

float precision in numpy arrays differ from their elements

I have values of numpy.float32 type, and a numpy array with dtype="float32".

When outputting the representation of the values directly using the individual array element references, I get a difference in precision than when I output the representation of the array object itself.

The ensuing calculations are also a bit off, so the latter value seems to be the one used in consequtive vector / matrix artihmetic.

Why is there a difference, and must these precision "anomalies" be handled manually?

>>> a = math.pi / 2

>>> a
1.5707963267948966

>>> elementx = numpy.float32(math.cos(a))

>>> arrayx = numpy.array([elementx], dtype="float32")

>>> elementx
6.1232343e-17

>>> arrayx
array([  6.12323426e-17], dtype=float32)

>>> t = numpy.float32(3.0)

>>> t * elementx
1.8369703e-16

>>> t * arrayx
array([  1.83697028e-16], dtype=float32)

(Python 3.5.2, GCC 5.4.0, linux 4.4.0-21-generic)

Upvotes: 0

Views: 200

Answers (1)

Stop harming Monica
Stop harming Monica

Reputation: 12590

These are just differences in the string representation, the values are the same and calculations are not off.

>>> (t * elementx) == (t * arrayx)[0]
True

Upvotes: 2

Related Questions