2

Executing the following code in a fresh Python 2.7.3 interpreter on my ubuntu linux machine gives the output shown after the code.

import numpy as np
p = [1/3., 1/2., 23/25., 1]
q = np.array(p)
r = list(q)
print p; print q; print r

Output:

[0.3333333333333333, 0.5, 0.92, 1]
[ 0.33333333  0.5         0.92        1.        ]
[0.33333333333333331, 0.5, 0.92000000000000004, 1.0]

I'm trying to figure out why p and r print out differently, but so far haven't got a plausible theory. Any ideas on why they differ?

2 Answers 2

3

They print differently because p is a list of float and int, whereas r is a list of numpy.float64:

In [23]: map(type, p)
Out[23]: [float, float, float, int]

In [24]: map(type, r)
Out[24]: [numpy.float64, numpy.float64, numpy.float64, numpy.float64]

This happens because NumPy arrays are of a uniform type, so everything gets widened to float64 when you create q.

The values in two lists compare equal, so it's purely a difference in formatting:

In [22]: p == r
Out[22]: True
Sign up to request clarification or add additional context in comments.

Comments

1

I think this is just a difference in how __repr__ is implemented for a np.float64 vs. a python float.

When you create a list out of your numpy array, you take the elements (with type np.float64) and put them in the list. So you have actually converted the types of your original data from float to np.float64.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.